repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/actions/content_security_policy.rb
lib/hanami/config/actions/content_security_policy.rb
# frozen_string_literal: true module Hanami class Config class Actions # Config for Content Security Policy in Hanami apps # # @since 2.0.0 class ContentSecurityPolicy # @since 2.0.0 # @api private def initialize(&blk) @policy = { base_uri: "'self'", child_src: "'self'", connect_src: "'self'", default_src: "'none'", font_src: "'self'", form_action: "'self'", frame_ancestors: "'self'", frame_src: "'self'", img_src: "'self' https: data:", media_src: "'self'", object_src: "'none'", script_src: "'self'", style_src: "'self' 'unsafe-inline' https:" } blk&.(self) end # @since 2.0.0 # @api private def initialize_copy(original_object) @policy = original_object.instance_variable_get(:@policy).dup super end # Get a CSP setting # # @param key [Symbol] the underscored name of the CPS setting # @return [String,NilClass] the CSP setting, if any # # @since 2.0.0 # @api public # # @example # module MyApp # class App < Hanami::App # config.actions.content_security_policy[:base_uri] # => "'self'" # end # end def [](key) @policy[key] end # Set a CSP setting # # @param key [Symbol] the underscored name of the CPS setting # @param value [String] the CSP setting value # # @since 2.0.0 # @api public # # @example Replace a default value # module MyApp # class App < Hanami::App # config.actions.content_security_policy[:plugin_types] = nil # end # end # # @example Append to a default value # module MyApp # class App < Hanami::App # config.actions.content_security_policy[:script_src] += " https://my.cdn.test" # end # end def []=(key, value) @policy[key] = value end # Deletes a CSP key # # @param key [Symbol] the underscored name of the CPS setting # # @since 2.0.0 # @api public # # @example # module MyApp # class App < Hanami::App # config.actions.content_security_policy.delete(:object_src) # end # end def delete(key) @policy.delete(key) end # Returns true if 'nonce' is used in any of the policies. # # @return [Boolean] # # @api public # @since 2.3.0 def nonce? @policy.any? { _2.match?(/'nonce'/) } end # Returns an array of middleware name to support 'nonce' in # policies, or an empty array if 'nonce' is not used. # # @return [Array<(Symbol, Array)>] # # @api public # @since 2.3.0 def middleware return [] unless nonce? [Hanami::Middleware::ContentSecurityPolicyNonce] end # @since 2.0.0 # @api private def to_s @policy.map do |key, value| "#{dasherize(key)} #{value}" end.join(";") end private # @since 2.0.0 # @api private def dasherize(key) key.to_s.gsub("_", "-") end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/actions/cookies.rb
lib/hanami/config/actions/cookies.rb
# frozen_string_literal: true module Hanami class Config class Actions # Wrapper for app-level config of HTTP cookies for Hanami actions. # # This decorates the hash of cookie options that is otherwise directly configurable on # actions, and adds the `enabled?` method to allow app base action to determine whether to # include the `Action::Cookies` module. # # @api public # @since 2.0.0 class Cookies # Returns the cookie options. # # @return [Hash] # # @api public # @since 2.0.0 attr_reader :options # Returns a new `Cookies`. # # You should not need to initialize this class directly. Instead use # {Hanami::Config::Actions#cookies}. # # @api private # @since 2.0.0 def initialize(options) @options = options end # Returns true if any cookie options have been provided. # # @return [Boolean] # # @api public # @since 2.0.0 def enabled? !options.nil? end # Returns the cookie options. # # If no options have been provided, returns an empty hash. # # @return [Hash] # # @api public def to_h options.to_h end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/config/actions/sessions.rb
lib/hanami/config/actions/sessions.rb
# frozen_string_literal: true require "hanami/utils/string" require "hanami/utils/class" module Hanami class Config class Actions # Config for HTTP session middleware in Hanami actions. # # @api public # @since 2.0.0 class Sessions # Returns the configured session storage # # @return [Symbol] # # @api public # @since 2.0.0 attr_reader :storage # Returns the configured session storage options # # @return [Array] # # @api public # @since 2.0.0 attr_reader :options # Returns a new `Sessions`. # # You should not need to initialize this class directly. Instead use # {Hanami::Config::Actions#sessions=}. # # @example # config.actions.sessions = :cookie, {secret: "xyz"} # # @api private # @since 2.0.0 def initialize(storage = nil, *options) @storage = storage @options = options end # Returns true if sessions have been enabled. # # @return [Boolean] # # @api public # @since 2.0.0 def enabled? !storage.nil? end # Returns an array of the session storage middleware name and its options, or an empty array # if sessions have not been enabled. # # @return [Array<(Symbol, Array)>] # # @api public # @since 2.0.0 def middleware return [] unless enabled? [storage_middleware, options].flatten(1) end private def storage_middleware require_storage name = Utils::String.classify(storage) Utils::Class.load!(name, ::Rack::Session) end def require_storage require "rack/session/#{storage}" end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice/router.rb
lib/hanami/slice/router.rb
# frozen_string_literal: true require "hanami/router" require_relative "routing/resolver" require_relative "routing/middleware/stack" module Hanami class Slice # `Hanami::Router` subclass with enhancements for use within Hanami apps. # # This is loaded from Hanami apps and slices and made available as their # {Hanami::Slice::ClassMethods#router router}. # # @api private class Router < ::Hanami::Router # @api private attr_reader :inflector # @api private attr_reader :middleware_stack # @api private attr_reader :path_prefix # @api private def initialize(routes:, inflector:, middleware_stack: Routing::Middleware::Stack.new, prefix: ::Hanami::Router::DEFAULT_PREFIX, **kwargs, &blk) @path_prefix = Hanami::Router::Prefix.new(prefix) @inflector = inflector @middleware_stack = middleware_stack @resource_scope = [] instance_eval(&blk) super(**kwargs, &routes) end # @api private def freeze return self if frozen? remove_instance_variable(:@middleware_stack) super end # @api private def to_rack_app middleware_stack.to_rack_app(self) end # @api private def use(*args, **kwargs, &blk) middleware_stack.use(*args, **kwargs.merge(path_prefix: path_prefix.to_s), &blk) end # Yields a block for routes to resolve their action components from the given slice. # # An optional URL prefix may be supplied with `at:`. # # @example # # config/routes.rb # # module MyApp # class Routes < Hanami::Routes # slice :admin, at: "/admin" do # # Will route to the "actions.posts.index" component in Admin::Slice # get "posts", to: "posts.index" # end # end # end # # @param slice_name [Symbol] the slice's name # @param at [String, nil] optional URL prefix for the routes # # @api public # @since 2.0.0 def slice(slice_name, at:, as: nil, &blk) blk ||= @resolver.find_slice(slice_name).routes prev_resolver = @resolver @resolver = @resolver.to_slice(slice_name) scope(at, as:, &blk) ensure @resolver = prev_resolver end # Generates RESTful routes for a plural resource. # # @param name [Symbol] the resource name (plural) # @param options [Hash] options for customizing the routes # @option options [Array<Symbol>] :only Limit to specific actions # @option options [Array<Symbol>] :except Exclude specific actions # @option options [String] :to the action key namespace, e.g. "namespace.action" # @option options [String] :path the URL path # @option options [String, Symbol] :as the route name prefix # # @example # resources :users # # Generates: # # GET /users users.index # # GET /users/new users.new # # POST /users users.create # # GET /users/:id users.show # # GET /users/:id/edit users.edit # # PATCH /users/:id users.update # # DELETE /users/:id users.destroy # # @api public # @since 2.3.0 def resources(name, **options, &block) build_resource(name, :plural, options, &block) end # Generates RESTful routes for a singular resource. # # @param name [Symbol] the resource name (singular) # @param options [Hash] options for customizing the routes # @option options [Array<Symbol>] :only limit to specific actions # @option options [Array<Symbol>] :except exclude specific actions # @option options [String] :to the action key namespace, e.g. "namespace.action" # @option options [String] :path the URL path # @option options [String, Symbol] :as the route name prefix # # @example # resource :profile # # Generates (singular, no index): # # GET /profile/new profile.new # # POST /profile profile.create # # GET /profile profile.show # # GET /profile/edit profile.edit # # PATCH /profile profile.update # # DELETE /profile profile.destroy # # @api public # @since 2.3.0 def resource(name, **options, &block) build_resource(name, :singular, options, &block) end private def build_resource(name, type, options, &block) resource_builder = ResourceBuilder.new( name: name, type: type, resource_scope: @resource_scope, options: options, inflector: inflector ) resource_builder.add_routes(self) resource_builder.scope(self, &block) if block end # Builds RESTful routes for a resource # # @api private class ResourceBuilder ROUTE_OPTIONS = { index: {method: :get}, new: {method: :get, path_suffix: "/new", name_prefix: "new"}, create: {method: :post}, show: {method: :get, path_suffix: "/:id"}, edit: {method: :get, path_suffix: "/:id/edit", name_prefix: "edit"}, update: {method: :patch, path_suffix: "/:id"}, destroy: {method: :delete, path_suffix: "/:id"} }.freeze PLURAL_ACTIONS = %i[index new create show edit update destroy].freeze SINGULAR_ACTIONS = (PLURAL_ACTIONS - %i[index]).freeze def initialize(name:, type:, resource_scope:, options:, inflector:) @name = name @type = type @resource_scope = resource_scope @options = options @inflector = inflector @path = options[:path] || name.to_s end def scope(router, &block) @resource_scope.push(@name) router.scope(scope_path, as: scope_name, &block) ensure @resource_scope.pop end def add_routes(router) actions.each do |action| add_route(router, action, ROUTE_OPTIONS.fetch(action)) end end private def plural? @type == :plural end def singular? !plural? end def scope_path if plural? "#{@path}/:#{@inflector.singularize(@path.to_s)}_id" else @path end end def scope_name @inflector.singularize(@name) end def actions default_actions = plural? ? PLURAL_ACTIONS : SINGULAR_ACTIONS if @options[:only] Array(@options[:only]) & default_actions elsif @options[:except] default_actions - Array(@options[:except]) else default_actions end end def add_route(router, action, route_options) path = "/#{@path}#{route_suffix(route_options[:path_suffix])}" to = "#{key_path_base}#{CONTAINER_KEY_DELIMITER}#{action}" as = route_name(action, route_options[:name_prefix]) router.public_send(route_options[:method], path, to:, as:) end def route_suffix(suffix) return suffix.sub(LEADING_ID_REGEX, "") if suffix && singular? suffix end LEADING_ID_REGEX = %r{\A/:id} def key_path_base @key_path_base ||= if @options[:to] @options[:to] else @name.to_s.then { |name| next name unless @resource_scope.any? prefix = @resource_scope.join(CONTAINER_KEY_DELIMITER) "#{prefix}#{CONTAINER_KEY_DELIMITER}#{name}" } end end def route_name(action, prefix) name = route_name_base name = @inflector.pluralize(name) if plural? && PLURALIZED_NAME_ACTIONS.include?(action) [prefix, name] end PLURALIZED_NAME_ACTIONS = %i[index create].freeze def route_name_base @route_name_base ||= if @options[:as] @options[:as].to_s elsif plural? @inflector.singularize(@name.to_s) else @name.to_s end end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice/routes_helper.rb
lib/hanami/slice/routes_helper.rb
# frozen_string_literal: true module Hanami class Slice # Hanami app routes helpers # # An instance of this class will be registered with slice (at the "routes" key). You # can use it to access the route helpers for your app. # # @example # MyApp::App["routes"].path(:root) # => "/" # # @see Hanami::Router::UrlHelpers # @since 2.0.0 class RoutesHelper # @since 2.0.0 # @api private def initialize(router) @router = router end # @see Hanami::Router::UrlHelpers#path def path(...) router.path(...) end # @see Hanami::Router::UrlHelpers#url def url(...) router.url(...) end private attr_reader :router end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice/view_name_inferrer.rb
lib/hanami/slice/view_name_inferrer.rb
# frozen_string_literal: true require_relative "../constants" module Hanami class Slice # Infers a view name for automatically rendering within actions. # # @api private # @since 2.0.0 class ViewNameInferrer ALTERNATIVE_NAMES = { "create" => "new", "update" => "edit" }.freeze class << self # Returns an array of container keys for views matching the given action. # # Also provides alternative view keys for common RESTful actions. # # @example # ViewNameInferrer.call(action_name: "Main::Actions::Posts::Create", slice: Main::Slice) # # => ["views.posts.create", "views.posts.new"] # # @param action_class_name [String] action class name # @param slice [Hanami::Slice, Hanami::Application] Hanami slice containing the action # # @return [Array<string>] array of paired view container keys def call(action_class_name:, slice:) action_key_base = slice.config.actions.name_inference_base view_key_base = slice.config.actions.view_name_inference_base action_name_key = action_name_key(action_class_name, slice, action_key_base) view_key = [view_key_base, action_name_key].compact.join(CONTAINER_KEY_DELIMITER) [view_key, alternative_view_key(view_key)].compact end private def action_name_key(action_name, slice, key_base) slice .inflector .underscore(action_name) .sub(%r{^#{slice.slice_name.path}#{PATH_DELIMITER}}, "") .sub(%r{^#{key_base}#{PATH_DELIMITER}}, "") .gsub("/", CONTAINER_KEY_DELIMITER) end def alternative_view_key(view_key) parts = view_key.split(CONTAINER_KEY_DELIMITER) alternative_name = ALTERNATIVE_NAMES[parts.last] return unless alternative_name [parts[0..-2], alternative_name].join(CONTAINER_KEY_DELIMITER) end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice/routing/resolver.rb
lib/hanami/slice/routing/resolver.rb
# frozen_string_literal: true module Hanami class Slice # @api private module Routing # Hanami app router endpoint resolver # # This resolves endpoints objects from a slice container using the strings passed to `to:` as # their container keys. # # @api private # @since 2.0.0 class Resolver SLICE_ACTIONS_KEY_NAMESPACE = "actions" # @api private # @since 2.0.0 def initialize(slice:) @slice = slice end # @api private # @since 2.0.0 def find_slice(slice_name) slice.slices[slice_name] end # @api private # @since 2.0.0 def to_slice(slice_name) self.class.new(slice: find_slice(slice_name)) end # @api private # @since 2.0.0 def call(_path, endpoint) endpoint = case endpoint when String resolve_slice_action(endpoint) when Class endpoint.respond_to?(:call) ? endpoint : endpoint.new else endpoint end unless endpoint.respond_to?(:call) raise Routes::NotCallableEndpointError.new(endpoint) end endpoint end private # @api private # @since 2.0.0 attr_reader :slice # @api private # @since 2.0.0 def resolve_slice_action(key) action_key = "#{SLICE_ACTIONS_KEY_NAMESPACE}.#{key}" ensure_action_in_slice(action_key) # Lazily resolve action from the slice to reduce router initialization time, and # circumvent endless loops from the action requiring access to router-related # concerns (which may not be fully loaded at the time of reading the routes) -> (*args) { action = slice.resolve(action_key) do raise Routes::MissingActionError.new(action_key, slice) end action.call(*args) } end def ensure_action_in_slice(key) return unless slice.booted? raise Routes::MissingActionError.new(key, slice) unless slice.key?(key) end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/slice/routing/middleware/stack.rb
lib/hanami/slice/routing/middleware/stack.rb
# frozen_string_literal: true require "hanami/router" require "hanami/middleware" require "hanami/middleware/app" require "hanami/errors" module Hanami class Slice module Routing # @since 2.0.0 # @api private module Middleware # Wraps a rack app with a middleware stack # # We use this class to add middlewares to the rack application generated from # {Hanami::Slice::Router}. # # ``` # stack = Hanami::Slice::Routing::Middleware::Stack.new # stack.use(Rack::ContentType, "text/html") # stack.to_rack_app(a_rack_app) # ``` # # Middlewares can be mounted on specific paths: # # ``` # stack.with("/api") do # stack.use(Rack::ContentType, "application/json") # end # ``` # # @see Hanami::Config#middleware # # @since 2.0.0 # @api private class Stack include Enumerable # @since 2.0.0 # @api private attr_reader :stack # Returns an array of Ruby namespaces from which to load middleware classes specified by # symbol names given to {#use}. # # Defaults to `[Hanami::Middleware]`. # # @return [Array<Object>] # # @api public # @since 2.0.0 attr_reader :namespaces # @since 2.0.0 # @api private def initialize @stack = Hash.new { |hash, key| hash[key] = [] } @namespaces = [Hanami::Middleware] end # @since 2.0.0 # @api private def initialize_copy(source) super @stack = stack.dup @namespaces = namespaces.dup end # Adds a middleware to the stack. # # @example # # Using a symbol name; adds Hanami::Middleware::BodyParser.new([:json]) # middleware.use :body_parser, :json # # # Using a class name # middleware.use MyMiddleware # # # Adding a middleware before or after others # middleware.use MyMiddleware, before: SomeMiddleware # middleware.use MyMiddleware, after: OtherMiddleware # # @param spec [Symbol, Class] the middleware name or class name # @param args [Array, nil] Arguments to pass to the middleware's `.new` method # @param before [Class, nil] an optional (already added) middleware class to add the # middleware before # @param after [Class, nil] an optional (already added) middleware class to add the # middleware after # # @return [self] # # @api public # @since 2.0.0 def use(spec, *args, path_prefix: ::Hanami::Router::DEFAULT_PREFIX, before: nil, after: nil, **kwargs, &blk) middleware = resolve_middleware_class(spec) item = [middleware, args, kwargs, blk] if before @stack[path_prefix].insert((idx = index_of(before, path_prefix)).zero? ? 0 : idx - 1, item) elsif after @stack[path_prefix].insert(index_of(after, path_prefix) + 1, item) else @stack[path_prefix].push(item) end self end # @since 2.0.0 # @api private def update(other) other.stack.each do |path_prefix, items| stack[path_prefix].concat(items) end self end # @since 2.0.0 # @api private def to_rack_app(app) unless Hanami.bundled?("rack") raise "Add \"rack\" to your `Gemfile` to run Hanami as a rack app" end mapping = to_hash return app if mapping.empty? Hanami::Middleware::App.new(app, mapping) end # @since 2.0.0 # @api private def to_hash @stack.each_with_object({}) do |(path, _), result| result[path] = stack_for(path) end end # @since 2.0.0 # @api private def empty? @stack.empty? end # @since 2.0.0 # @api private def each(&blk) @stack.each(&blk) end # @since 2.0.0 # @api private def mapped(builder, prefix, &blk) if prefix == ::Hanami::Router::DEFAULT_PREFIX builder.instance_eval(&blk) else builder.map(prefix, &blk) end end private # @since 2.0.0 def index_of(middleware, path_prefix) @stack[path_prefix].index { |(m, *)| m.equal?(middleware) } end # @since 2.0.0 # @api private def stack_for(current_path) @stack.each_with_object([]) do |(path, stack), result| next unless current_path.start_with?(path) result.push(stack) end.flatten(1) end # @since 2.0.0 def resolve_middleware_class(spec) case spec when Symbol then load_middleware_class(spec) when Class, Module then spec else if spec.respond_to?(:call) spec else raise UnsupportedMiddlewareSpecError, spec end end end # @since 2.0.0 def load_middleware_class(spec) begin require "hanami/middleware/#{spec}" rescue LoadError # rubocop:disable Lint/SuppressedException end # FIXME: Classify must use App inflector class_name = Hanami::Utils::String.classify(spec.to_s) namespace = namespaces.detect { |ns| ns.const_defined?(class_name) } if namespace namespace.const_get(class_name) else raise( UnsupportedMiddlewareSpecError, "Failed to find corresponding middleware class for `#{spec}` in #{namespaces.join(', ')}" ) end end end end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/web/rack_logger.rb
lib/hanami/web/rack_logger.rb
# frozen_string_literal: true require "delegate" require "json" module Hanami # @api private module Web # Rack logger for Hanami apps # # @api private # @since 2.0.0 class RackLogger EMPTY_PARAMS = {}.freeze private_constant :EMPTY_PARAMS REQUEST_METHOD = "REQUEST_METHOD" private_constant :REQUEST_METHOD HTTP_X_FORWARDED_FOR = "HTTP_X_FORWARDED_FOR" private_constant :HTTP_X_FORWARDED_FOR REMOTE_ADDR = "REMOTE_ADDR" private_constant :REMOTE_ADDR SCRIPT_NAME = "SCRIPT_NAME" private_constant :SCRIPT_NAME PATH_INFO = "PATH_INFO" private_constant :PATH_INFO ROUTER_PARAMS = "router.params" private_constant :ROUTER_PARAMS CONTENT_LENGTH = "CONTENT_LENGTH" private_constant :CONTENT_LENGTH MILLISECOND = "ms" private_constant :MILLISECOND MICROSECOND = "µs" private_constant :MICROSECOND # Dynamic extension used in development and test environments # @api private module Development private # @since 2.0.0 # @api private def data(env, status:, elapsed:) payload = super payload.delete(:elapsed_unit) payload[:elapsed] = elapsed > 1000 ? "#{elapsed / 1000}ms" : "#{elapsed}#{MICROSECOND}" payload end end # @since 2.1.0 # @api private class UniversalLogger class << self # @since 2.1.0 # @api private def call(logger) return logger if compatible_logger?(logger) new(logger) end # @since 2.1.0 # @api private alias_method :[], :call private def compatible_logger?(logger) logger.respond_to?(:tagged) && accepts_entry_payload?(logger) end def accepts_entry_payload?(logger) logger.method(:info).parameters.any? { |(type, _)| type == :keyrest } end end # @since 2.1.0 # @api private attr_reader :logger # @since 2.1.0 # @api private def initialize(logger) @logger = logger end # @since 2.1.0 # @api private def tagged(*, &blk) blk.call end # Logs the entry as JSON. # # This ensures a reasonable (and parseable) representation of our log payload structures for # loggers that are configured to wholly replace Hanami's default logger. # # @since 2.1.0 # @api private def info(message = nil, **payload, &blk) logger.info do if blk JSON.generate(blk.call) else payload[:message] = message if message JSON.generate(payload) end end end # @see info # # @since 2.1.0 # @api private def error(message = nil, **payload, &blk) logger.error do if blk JSON.generate(blk.call) else payload[:message] = message if message JSON.generate(payload) end end end end # @api private # @since 2.0.0 def initialize(logger, env: :development) @logger = UniversalLogger[logger] extend(Development) if %i[development test].include?(env) end # @api private # @since 2.0.0 def attach(rack_monitor) rack_monitor.on :stop do |event| log_request event[:env], event[:status], event[:time] end rack_monitor.on :error do |event| # TODO: why we don't provide time on error? log_exception event[:env], event[:exception], 500, 0 end end # @api private # @since 2.0.0 def log_request(env, status, elapsed) logger.tagged(:rack) do logger.info do data(env, status: status, elapsed: elapsed) end end end # @api private # @since 2.0.0 def log_exception(env, exception, status, elapsed) logger.tagged(:rack) do logger.error(exception) do data(env, status: status, elapsed: elapsed) end end end private attr_reader :logger # @api private # @since 2.0.0 def data(env, status:, elapsed:) { verb: env[REQUEST_METHOD], status: status, ip: env[HTTP_X_FORWARDED_FOR] || env[REMOTE_ADDR], path: "#{env[SCRIPT_NAME]}#{env[PATH_INFO]}", length: extract_content_length(env), params: env.fetch(ROUTER_PARAMS, EMPTY_PARAMS), elapsed: elapsed, elapsed_unit: MICROSECOND, } end # @api private # @since 2.0.0 def extract_content_length(env) value = env[CONTENT_LENGTH] !value || value.to_s == "0" ? "-" : value end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
hanami/hanami
https://github.com/hanami/hanami/blob/ccc7e5df285595191fb467729bb5ddc53f77f077/lib/hanami/web/welcome.rb
lib/hanami/web/welcome.rb
# frozen_string_literal: true require "erb" module Hanami # @api private module Web # Middleware that renders a welcome view in fresh Hanami apps. # # @api private # @since 2.1.0 class Welcome # @api private # @since 2.1.0 def initialize(app) @app = app end # @api private # @since 2.1.0 def call(env) request_path = env["REQUEST_PATH"] || "" request_host = env["HTTP_HOST"] || "" template_path = File.join(__dir__, "welcome.html.erb") body = [ERB.new(File.read(template_path)).result(binding)] [200, {}, body] end private # @api private # @since 2.1.0 def hanami_version Hanami::VERSION end # @api private # @since 2.1.0 def ruby_version RUBY_DESCRIPTION end end end end
ruby
MIT
ccc7e5df285595191fb467729bb5ddc53f77f077
2026-01-04T15:40:32.670663Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/init.rb
init.rb
require 'geocoder'
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/mongoid_test_helper.rb
test/mongoid_test_helper.rb
require 'rubygems' require 'test/unit' require 'test_helper' require 'mongoid' require 'geocoder/models/mongoid' $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) if (::Mongoid::VERSION >= "3") Mongoid.logger = Logger.new($stderr, :debug) else Mongoid.configure do |config| config.logger = Logger.new($stderr, :debug) end end ## # Geocoded model. # class PlaceUsingMongoid include Mongoid::Document include Geocoder::Model::Mongoid geocoded_by :address, :coordinates => :location field :name field :address field :location, :type => Array def initialize(name, address) super() write_attribute :name, name write_attribute :address, address end end class PlaceUsingMongoidWithoutIndex include Mongoid::Document include Geocoder::Model::Mongoid field :location, :type => Array geocoded_by :location, :skip_index => true end class PlaceUsingMongoidReverseGeocoded include Mongoid::Document include Geocoder::Model::Mongoid field :address field :coordinates, :type => Array reverse_geocoded_by :coordinates def initialize(name, latitude, longitude) super() write_attribute :name, name write_attribute :coordinates, [latitude, longitude] end end class PlaceUsingMongoidWithCustomResultsHandling include Mongoid::Document include Geocoder::Model::Mongoid field :location, :type => Array field :coords_string field :name field :address geocoded_by :address, :coordinates => :location do |obj,results| if result = results.first obj.coords_string = "#{result.latitude},#{result.longitude}" else obj.coords_string = "NOT FOUND" end end def initialize(name, address) super() write_attribute :name, name write_attribute :address, address end end class PlaceUsingMongoidReverseGeocodedWithCustomResultsHandling include Mongoid::Document include Geocoder::Model::Mongoid field :name field :country field :coordinates, :type => Array reverse_geocoded_by :coordinates do |obj,results| if result = results.first obj.country = result.country_code end end def initialize(name, latitude, longitude) super() write_attribute :name, name write_attribute :coordinates, [latitude, longitude] end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/test_helper.rb
test/test_helper.rb
# encoding: utf-8 require 'rubygems' require 'test/unit' $LOAD_PATH.unshift(File.dirname(__FILE__)) $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib')) require 'yaml' configs = YAML.load_file('test/database.yml') if configs.keys.include? ENV['DB'] require 'active_record' # Establish a database connection ActiveRecord::Base.configurations = configs db_name = ENV['DB'] if db_name == 'sqlite' && ENV['USE_SQLITE_EXT'] == '1' then gem 'sqlite_ext' require 'sqlite_ext' SqliteExt.register_ruby_math end ActiveRecord::Base.establish_connection(db_name.to_sym) ActiveRecord::Base.default_timezone = :utc if defined? ActiveRecord::MigrationContext if ActiveRecord.version.release < Gem::Version.new('6.0.0') # ActiveRecord >=5.2, takes one argument ActiveRecord::MigrationContext.new('test/db/migrate').migrate else # ActiveRecord >=6.0, takes two arguments ActiveRecord::MigrationContext.new('test/db/migrate', nil).migrate end else ActiveRecord::Migrator.migrate('test/db/migrate', nil) end else class MysqlConnection def adapter_name "mysql" end end ## # Simulate enough of ActiveRecord::Base that objects can be used for testing. # module ActiveRecord class Base def initialize @attributes = {} end def read_attribute(attr_name) @attributes[attr_name.to_sym] end def write_attribute(attr_name, value) @attributes[attr_name.to_sym] = value end def update_attribute(attr_name, value) write_attribute(attr_name.to_sym, value) end def self.scope(*args); end def self.connection MysqlConnection.new end def method_missing(name, *args, &block) if name.to_s[-1..-1] == "=" write_attribute name.to_s[0...-1], *args else read_attribute name end end class << self def table_name 'test_table_name' end def primary_key :id end def maximum(_field) 1.0 end end end end end # simulate Rails module so Railtie gets loaded module Rails end # Require Geocoder after ActiveRecord simulator. require 'geocoder' require 'geocoder/lookups/base' # and initialize Railtie manually (since Rails::Railtie doesn't exist) Geocoder::Railtie.insert ## # Mock HTTP request to geocoding service. # module Geocoder module Lookup class Base private def fixture_exists?(filename) File.exist?(File.join("test", "fixtures", filename)) end def read_fixture(file) filepath = File.join("test", "fixtures", file) s = File.read(filepath).strip.gsub(/\n\s*/, "") MockHttpResponse.new(body: s, code: "200") end ## # Fixture to use if none match the given query. # def default_fixture_filename "#{fixture_prefix}_madison_square_garden" end def fixture_prefix handle end def fixture_for_query(query) label = query.reverse_geocode? ? "reverse" : query.text.gsub(/[ ,\.]+/, "_").downcase filename = "#{fixture_prefix}_#{label}" fixture_exists?(filename) ? filename : default_fixture_filename end # This alias allows us to use this method in further tests # to actually test http requests alias_method :actual_make_api_request, :make_api_request remove_method(:make_api_request) def make_api_request(query) raise Timeout::Error if query.text == "timeout" raise SocketError if query.text == "socket_error" raise Errno::ECONNREFUSED if query.text == "connection_refused" raise Errno::EHOSTUNREACH if query.text == "host_unreachable" if query.text == "invalid_json" return MockHttpResponse.new(:body => 'invalid json', :code => 200) end read_fixture fixture_for_query(query) end end require 'geocoder/lookups/bing' class Bing private def read_fixture(file) if file == "bing_service_unavailable" filepath = File.join("test", "fixtures", file) s = File.read(filepath).strip.gsub(/\n\s*/, "") MockHttpResponse.new(body: s, code: "200", headers: {'x-ms-bm-ws-info' => "1"}) else super end end end require 'geocoder/lookups/db_ip_com' class DbIpCom private def fixture_prefix "db_ip_com" end end require 'geocoder/lookups/google_premier' class GooglePremier private def fixture_prefix "google" end end require 'geocoder/lookups/google_places_details' class GooglePlacesDetails private def fixture_prefix "google_places_details" end end require 'geocoder/lookups/location_iq' class LocationIq private def fixture_prefix "location_iq" end end require 'geocoder/lookups/yandex' class Yandex private def default_fixture_filename "yandex_kremlin" end end require 'geocoder/lookups/abstract_api' class AbstractApi private def default_fixture_filename "abstract_api" end end require 'geocoder/lookups/freegeoip' class Freegeoip private def default_fixture_filename "freegeoip_74_200_247_59" end end require 'geocoder/lookups/ipbase' class Ipbase private def default_fixture_filename "ipbase_74_200_247_59" end end require 'geocoder/lookups/ip2location' class Ip2location private def default_fixture_filename "ip2location_8_8_8_8" end end require 'geocoder/lookups/ip2location_io' class Ip2locationIo private def default_fixture_filename "ip2location_io_8_8_8_8" end end require 'geocoder/lookups/ip2location_lite' class Ip2locationLite private remove_method(:results) def results query return [] if query.to_s == "no results" if query.to_s == '127.0.0.1' [{:country_short=>"-", :country_long=>"-", :region=>"-", :city=>"-", :latitude=>0.0, :longitude=>0.0, :zipcode=>"-", :timezone=>"-", :isp=>"Loopback", :domain=>"-", :netspeed=>"-", :iddcode=>"-", :areacode=>"-", :weatherstationcode=>"-", :weatherstationname=>"-", :mcc=>"-", :mnc=>"-", :mobilebrand=>"-", :elevation=>0, :usagetype=>"RSV", :addresstype=>"U", :category=>"IAB24", :district=>"-", :asn=>"-", :as=>"-"}] elsif query.to_s == '8.8.8.8' [{:country_short=>"US", :country_long=>"United States of America", :region=>"California", :city=>"Mountain View", :latitude=>37.40599060058594, :longitude=>-122.0785140991211, :zipcode=>"94043", :timezone=>"-07:00", :isp=>"Google LLC", :domain=>"google.com", :netspeed=>"T1", :iddcode=>"1", :areacode=>"650", :weatherstationcode=>"USCA0746", :weatherstationname=>"Mountain View", :mcc=>"-", :mnc=>"-", :mobilebrand=>"-", :elevation=>32, :usagetype=>"DCH", :addresstype=>"A", :category=>"IAB19-11", :district=>"San Diego County", :asn=>"15169", :as=>"Google LLC"}] end end end require 'geocoder/lookups/ipgeolocation' class Ipgeolocation private def default_fixture_filename "ipgeolocation_103_217_177_217" end end require 'geocoder/lookups/ipqualityscore' class Ipqualityscore private def default_fixture_filename "ipqualityscore_74_200_247_59" end end require 'geocoder/lookups/ipstack' class Ipstack private def default_fixture_filename "ipstack_134_201_250_155" end end require 'geocoder/lookups/geoip2' class Geoip2 private remove_method(:results) def results(query) return [] if query.to_s == 'no results' return [] if query.to_s == '127.0.0.1' [{'city'=>{'names'=>{'en'=>'Mountain View', 'ru'=>'Маунтин-Вью'}},'country'=>{'iso_code'=>'US','names'=> {'en'=>'United States'}},'location'=>{'latitude'=>37.41919999999999, 'longitude'=>-122.0574},'postal'=>{'code'=>'94043'},'subdivisions'=>[{ 'iso_code'=>'CA','names'=>{'en'=>'California'}}]}] end def default_fixture_filename 'geoip2_74_200_247_59' end end require 'geocoder/lookups/telize' class Telize private def default_fixture_filename "telize_74_200_247_59" end end require 'geocoder/lookups/pointpin' class Pointpin private def default_fixture_filename "pointpin_80_111_55_55" end end require 'geocoder/lookups/maxmind' class Maxmind private def default_fixture_filename "maxmind_74_200_247_59" end end require 'geocoder/lookups/maxmind_geoip2' class MaxmindGeoip2 private def default_fixture_filename "maxmind_geoip2_1_2_3_4" end end require 'geocoder/lookups/maxmind_local' class MaxmindLocal private remove_method(:results) def results query return [] if query.to_s == "no results" if query.to_s == '127.0.0.1' [] else [{:request=>"8.8.8.8", :ip=>"8.8.8.8", :country_code2=>"US", :country_code3=>"USA", :country_name=>"United States", :continent_code=>"NA", :region_name=>"CA", :city_name=>"Mountain View", :postal_code=>"94043", :latitude=>37.41919999999999, :longitude=>-122.0574, :dma_code=>807, :area_code=>650, :timezone=>"America/Los_Angeles"}] end end end require 'geocoder/lookups/baidu' class Baidu private def default_fixture_filename "baidu_shanghai_pearl_tower" end end require 'geocoder/lookups/nationaal_georegister_nl' class NationaalGeoregisterNl private def default_fixture_filename "nationaal_georegister_nl" end end require 'geocoder/lookups/pdok_nl' class PdokNl private def default_fixture_filename "pdok_nl" end end require 'geocoder/lookups/baidu_ip' class BaiduIp private def default_fixture_filename "baidu_ip_202_198_16_3" end end require 'geocoder/lookups/tencent' class Tencent private def default_fixture_filename "tencent_shanghai_pearl_tower" end end require 'geocoder/lookups/geocodio' class Geocodio private def default_fixture_filename "geocodio_1101_pennsylvania_ave" end end require 'geocoder/lookups/melissa_street' class MelissaStreet private def default_fixture_filename "melissa_street_oakland_city_hall" end end require 'geocoder/lookups/postcode_anywhere_uk' class PostcodeAnywhereUk private def fixture_prefix 'postcode_anywhere_uk_geocode_v2_00' end def default_fixture_filename "#{fixture_prefix}_romsey" end end require 'geocoder/lookups/postcodes_io' class PostcodesIo private def fixture_prefix 'postcodes_io' end def default_fixture_filename "#{fixture_prefix}_malvern_hills" end end require 'geocoder/lookups/uk_ordnance_survey_names' class Geocoder::Lookup::UkOrdnanceSurveyNames private def default_fixture_filename "#{fixture_prefix}_london" end end require 'geocoder/lookups/geoportail_lu' class GeoportailLu private def fixture_prefix "geoportail_lu" end def default_fixture_filename "#{fixture_prefix}_boulevard_royal" end end require 'geocoder/lookups/latlon' class Latlon private def default_fixture_filename "latlon_6000_universal_blvd" end end require 'geocoder/lookups/ipinfo_io' class IpinfoIo private def default_fixture_filename "ipinfo_io_8_8_8_8" end end require 'geocoder/lookups/ipinfo_io_lite' class IpinfoIoLite private def default_fixture_filename "ipinfo_io_lite_8_8_8_8" end end require 'geocoder/lookups/ipregistry' class Ipregistry private def default_fixture_filename "ipregistry_8_8_8_8" end end require 'geocoder/lookups/ipapi_com' class IpapiCom private def default_fixture_filename "ipapi_com_74_200_247_59" end end require 'geocoder/lookups/ipdata_co' class IpdataCo private def default_fixture_filename "ipdata_co_74_200_247_59" end end require 'geocoder/lookups/ban_data_gouv_fr' class BanDataGouvFr private def fixture_prefix "ban_data_gouv_fr" end def default_fixture_filename "#{fixture_prefix}_rue_yves_toudic" end end require 'geocoder/lookups/amap' class Amap private def default_fixture_filename "amap_shanghai_pearl_tower" end end require 'geocoder/lookups/pickpoint' class Pickpoint private def fixture_prefix "pickpoint" end end require 'geocoder/lookups/twogis' class Twogis private def default_fixture_filename "twogis_kremlin" end end require 'geocoder/lookups/amazon_location_service' MockResults = Struct.new(:results) MockAWSPlaceGeometry = Struct.new(:point) MockAWSPlace = Struct.new(*%i[ address_number country geometry label municipality neighborhood postal_code region street sub_region ]) MockAWSResult = Struct.new(:place_id, :place) class MockAmazonLocationServiceClient def search_place_index_for_position(params = {}, options = {}) # Amazon transposes latitude and longitude, so our client does too on the outbound call and inbound data return mock_results if params[:position] == ["-75.676333", "45.423733"] mock_no_results end def search_place_index_for_text(params = {}, options = {}) return mock_results if params[:text].include? "Madison Square Garden" mock_no_results end private def fixture eval File.read File.join("test", "fixtures", "amazon_location_service_madison_square_garden") end def mock_results fixture_copy = fixture.dup place_id = fixture_copy.shift place = MockAWSPlace.new(*fixture_copy) MockResults.new([MockAWSResult.new(place_id, place)]) end def mock_no_results MockResults.new([]) end end class AmazonLocationService private def client MockAmazonLocationServiceClient.new end end require 'geocoder/lookups/geoapify' class Geoapify private def read_fixture(file) filepath = File.join("test", "fixtures", file) s = File.read(filepath).strip.gsub(/\n\s*/, "") options = { body: s, code: 200 } if file == "geoapify_invalid_request" options[:code] = 500 elsif file == "geoapify_invalid_key" options[:code] = 401 end MockHttpResponse.new(options) end end require 'geocoder/lookups/photon' class Photon private def read_fixture(file) filepath = File.join("test", "fixtures", file) s = File.read(filepath).strip.gsub(/\n\s*/, "") options = { body: s, code: 200 } if file == "photon_invalid_request" options[:code] = 400 end MockHttpResponse.new(options) end end end end ## # Geocoded model. # class Place < ActiveRecord::Base geocoded_by :address def initialize(name, address) super() write_attribute :name, name write_attribute :address, address end end ## # Geocoded model. # - Has user-defined primary key (not just 'id') # class PlaceWithCustomPrimaryKey < Place class << self def primary_key :custom_primary_key_id end end end class PlaceReverseGeocoded < ActiveRecord::Base reverse_geocoded_by :latitude, :longitude def initialize(name, latitude, longitude) super() write_attribute :name, name write_attribute :latitude, latitude write_attribute :longitude, longitude end end class PlaceWithCustomResultsHandling < ActiveRecord::Base geocoded_by :address do |obj,results| if result = results.first obj.coords_string = "#{result.latitude},#{result.longitude}" else obj.coords_string = "NOT FOUND" end end def initialize(name, address) super() write_attribute :name, name write_attribute :address, address end end class PlaceReverseGeocodedWithCustomResultsHandling < ActiveRecord::Base reverse_geocoded_by :latitude, :longitude do |obj,results| if result = results.first obj.country = result.country_code end end def initialize(name, latitude, longitude) super() write_attribute :name, name write_attribute :latitude, latitude write_attribute :longitude, longitude end end class PlaceWithForwardAndReverseGeocoding < ActiveRecord::Base geocoded_by :address, :latitude => :lat, :longitude => :lon reverse_geocoded_by :lat, :lon, :address => :location def initialize(name) super() write_attribute :name, name end end class PlaceWithCustomLookup < ActiveRecord::Base geocoded_by :address, :lookup => :nominatim do |obj,results| if result = results.first obj.result_class = result.class end end def initialize(name, address) super() write_attribute :name, name write_attribute :address, address end end class PlaceWithCustomLookupProc < ActiveRecord::Base geocoded_by :address, :lookup => lambda{|obj| obj.custom_lookup } do |obj,results| if result = results.first obj.result_class = result.class end end def custom_lookup :nominatim end def initialize(name, address) super() write_attribute :name, name write_attribute :address, address end end class PlaceReverseGeocodedWithCustomLookup < ActiveRecord::Base reverse_geocoded_by :latitude, :longitude, :lookup => :nominatim do |obj,results| if result = results.first obj.result_class = result.class end end def initialize(name, latitude, longitude) super() write_attribute :name, name write_attribute :latitude, latitude write_attribute :longitude, longitude end end class GeocoderTestCase < Test::Unit::TestCase self.test_order = :random def setup super Geocoder::Configuration.initialize Geocoder.configure( :maxmind => {:service => :city_isp_org}, :maxmind_geoip2 => {:service => :insights, :basic_auth => {:user => "user", :password => "password"}}) end def geocoded_object_params(abbrev) { :msg => ["Madison Square Garden", "4 Penn Plaza, New York, NY"] }[abbrev] end def reverse_geocoded_object_params(abbrev) { :msg => ["Madison Square Garden", 40.750354, -73.993371] }[abbrev] end def set_api_key!(lookup_name) lookup = Geocoder::Lookup.get(lookup_name) if lookup.required_api_key_parts.size == 1 key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' elsif lookup.required_api_key_parts.size > 1 key = lookup.required_api_key_parts else key = nil end Geocoder.configure(:api_key => key) end end class MockHttpResponse attr_reader :code, :body def initialize(options = {}) @code = options[:code].to_s @body = options[:body] @headers = options[:headers] || {} end def [](key) @headers[key] end end module MockLookup end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/db/migrate/001_create_test_schema.rb
test/db/migrate/001_create_test_schema.rb
# CreateTestSchema creates the tables used in test_helper.rb superclass = ActiveRecord::Migration # TODO: Inherit from the 5.0 Migration class directly when we drop support for Rails 4. superclass = ActiveRecord::Migration[5.0] if superclass.respond_to?(:[]) class CreateTestSchema < superclass def self.up [ :places, :place_reverse_geocodeds ].each do |table| create_table table do |t| t.column :name, :string t.column :address, :string t.column :latitude, :decimal, :precision => 16, :scale => 6 t.column :longitude, :decimal, :precision => 16, :scale => 6 t.column :radius_column, :decimal, :precision => 16, :scale => 6 end end [ :place_with_custom_lookup_procs, :place_with_custom_lookups, :place_reverse_geocoded_with_custom_lookups ].each do |table| create_table table do |t| t.column :name, :string t.column :address, :string t.column :latitude, :decimal, :precision => 16, :scale => 6 t.column :longitude, :decimal, :precision => 16, :scale => 6 t.column :result_class, :string end end create_table :place_with_forward_and_reverse_geocodings do |t| t.column :name, :string t.column :location, :string t.column :lat, :decimal, :precision => 16, :scale => 6 t.column :lon, :decimal, :precision => 16, :scale => 6 t.column :address, :string end create_table :place_reverse_geocoded_with_custom_results_handlings do |t| t.column :name, :string t.column :address, :string t.column :latitude, :decimal, :precision => 16, :scale => 6 t.column :longitude, :decimal, :precision => 16, :scale => 6 t.column :country, :string end create_table :place_with_custom_results_handlings do |t| t.column :name, :string t.column :address, :string t.column :latitude, :decimal, :precision => 16, :scale => 6 t.column :longitude, :decimal, :precision => 16, :scale => 6 t.column :coords_string, :string end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/ip_address_test.rb
test/unit/ip_address_test.rb
# encoding: utf-8 require 'test_helper' class IpAddressTest < GeocoderTestCase def test_valid assert Geocoder::IpAddress.new("232.65.123.94").valid? assert Geocoder::IpAddress.new(IPAddr.new("232.65.123.94")).valid? assert !Geocoder::IpAddress.new("666.65.123.94").valid? assert Geocoder::IpAddress.new("::ffff:12.34.56.78").valid? assert Geocoder::IpAddress.new("3ffe:0b00:0000:0000:0001:0000:0000:000a").valid? assert Geocoder::IpAddress.new(IPAddr.new("3ffe:0b00:0000:0000:0001:0000:0000:000a")).valid? assert Geocoder::IpAddress.new("::1").valid? assert !Geocoder::IpAddress.new("232.65.123.94.43").valid? assert !Geocoder::IpAddress.new("232.65.123").valid? assert !Geocoder::IpAddress.new("::ffff:123.456.789").valid? assert !Geocoder::IpAddress.new("Test\n232.65.123.94").valid? assert Geocoder::IpAddress.new("[3ffe:0b00:000:0000:0001:0000:0000:000a]:80").valid? end def test_internal assert Geocoder::IpAddress.new("0.0.0.0").internal? assert Geocoder::IpAddress.new("127.0.0.1").internal? assert Geocoder::IpAddress.new("::1").internal? assert Geocoder::IpAddress.new("172.19.0.1").internal? assert Geocoder::IpAddress.new("10.100.100.1").internal? assert Geocoder::IpAddress.new("192.168.0.1").internal? assert !Geocoder::IpAddress.new("232.65.123.234").internal? assert !Geocoder::IpAddress.new("127 Main St.").internal? assert !Geocoder::IpAddress.new("John Doe\n127 Main St.\nAnywhere, USA").internal? end def test_loopback assert Geocoder::IpAddress.new("0.0.0.0").loopback? assert Geocoder::IpAddress.new("127.0.0.1").loopback? assert Geocoder::IpAddress.new("::1").loopback? assert !Geocoder::IpAddress.new("172.19.0.1").loopback? assert !Geocoder::IpAddress.new("10.100.100.1").loopback? assert !Geocoder::IpAddress.new("192.168.0.1").loopback? assert !Geocoder::IpAddress.new("232.65.123.234").loopback? assert !Geocoder::IpAddress.new("127 Main St.").loopback? assert !Geocoder::IpAddress.new("John Doe\n127 Main St.\nAnywhere, USA").loopback? end def test_private assert Geocoder::IpAddress.new("172.19.0.1").private? assert Geocoder::IpAddress.new("10.100.100.1").private? assert Geocoder::IpAddress.new("192.168.0.1").private? assert !Geocoder::IpAddress.new("0.0.0.0").private? assert !Geocoder::IpAddress.new("127.0.0.1").private? assert !Geocoder::IpAddress.new("::1").private? assert !Geocoder::IpAddress.new("232.65.123.234").private? assert !Geocoder::IpAddress.new("127 Main St.").private? assert !Geocoder::IpAddress.new("John Doe\n127 Main St.\nAnywhere, USA").private? end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/logger_test.rb
test/unit/logger_test.rb
# encoding: utf-8 require 'test_helper' require 'logger' require 'tempfile' class LoggerTest < GeocoderTestCase def setup @tempfile = Tempfile.new("log") @logger = Logger.new(@tempfile.path) Geocoder.configure(logger: @logger) end def teardown @logger.close @tempfile.close end def test_set_logger_logs assert_equal nil, Geocoder.log(:warn, "should log") assert_match(/should log\n$/, @tempfile.read) end def test_logger_does_not_log_severity_too_low @logger.level = Logger::ERROR Geocoder.log(:info, "should not log") assert_equal "", @tempfile.read end def test_logger_logs_when_severity_high_enough @logger.level = Logger::DEBUG Geocoder.log(:warn, "important: should log!") assert_match(/important: should log/, @tempfile.read) end def test_kernel_logger_does_not_log_severity_too_low assert_nothing_raised do Geocoder.configure(logger: :kernel, kernel_logger_level: ::Logger::FATAL) Geocoder.log(:info, "should not log") end end def test_kernel_logger_logs_when_severity_high_enough assert_raises RuntimeError do Geocoder.configure(logger: :kernel, kernel_logger_level: ::Logger::DEBUG) Geocoder.log(:error, "important: should log!") end end def test_raise_configruation_error_for_invalid_logger Geocoder.configure(logger: {}) assert_raises Geocoder::ConfigurationError do Geocoder.log(:info, "should raise error") end end def test_set_logger_always_returns_nil assert_equal nil, Geocoder.log(:info, "should log") end def test_kernel_logger_always_returns_nil Geocoder.configure(logger: :kernel) silence_warnings do assert_equal nil, Geocoder.log(:warn, "should log") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/test_mode_test.rb
test/unit/test_mode_test.rb
# encoding: utf-8 require 'test_helper' class TestModeTest < GeocoderTestCase def setup @_original_lookup = Geocoder.config.lookup Geocoder.configure(:lookup => :test) end def teardown Geocoder::Lookup::Test.reset Geocoder.configure(:lookup => @_original_lookup) end def test_search_with_known_stub Geocoder::Lookup::Test.add_stub("New York, NY", [mock_attributes]) results = Geocoder.search("New York, NY") result = results.first assert_equal 1, results.size mock_attributes.each_key do |attr| assert_equal mock_attributes[attr], result.send(attr) end end def test_search_with_unknown_stub_without_default assert_raise ArgumentError do Geocoder.search("New York, NY") end end def test_search_with_unknown_stub_with_default Geocoder::Lookup::Test.set_default_stub([mock_attributes]) results = Geocoder.search("Atlantis, OC") result = results.first assert_equal 1, results.size mock_attributes.keys.each do |attr| assert_equal mock_attributes[attr], result.send(attr) end end def test_search_with_custom_attributes custom_attributes = mock_attributes.merge(:custom => 'NY, NY') Geocoder::Lookup::Test.add_stub("New York, NY", [custom_attributes]) result = Geocoder.search("New York, NY").first assert_equal 'NY, NY', result.custom end def test_search_with_invalid_address_stub Geocoder::Lookup::Test.add_stub("invalid address/no result", []) result = Geocoder.search("invalid address/no result") assert_equal [], result end def test_unsetting_stub Geocoder::Lookup::Test.add_stub("New York, NY", [mock_attributes]) assert_nothing_raised ArgumentError do Geocoder.search("New York, NY") end Geocoder::Lookup::Test.delete_stub("New York, NY") assert_raise ArgumentError do Geocoder.search("New York, NY") end end private def mock_attributes coordinates = [40.7143528, -74.0059731] @mock_attributes ||= { 'coordinates' => coordinates, 'latitude' => coordinates[0], 'longitude' => coordinates[1], 'address' => 'New York, NY, USA', 'state' => 'New York', 'state_code' => 'NY', 'country' => 'United States', 'country_code' => 'US', } end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/active_record_test.rb
test/unit/active_record_test.rb
# encoding: utf-8 require 'test_helper' class ActiveRecordTest < GeocoderTestCase def test_exclude_condition_when_model_has_a_custom_primary_key venue = PlaceWithCustomPrimaryKey.new(*geocoded_object_params(:msg)) # just call private method directly so we don't have to stub .near scope conditions = venue.class.send(:add_exclude_condition, ["fake_condition"], venue) assert_match( /#{PlaceWithCustomPrimaryKey.primary_key}/, conditions.join) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/mongoid_test.rb
test/unit/mongoid_test.rb
# encoding: utf-8 require 'mongoid_test_helper' class MongoidTest < GeocoderTestCase def test_geocoded_check p = PlaceUsingMongoid.new(*geocoded_object_params(:msg)) p.location = [40.750354, -73.993371] assert p.geocoded? end def test_geocoded_check_single_coord p = PlaceUsingMongoid.new(*geocoded_object_params(:msg)) p.location = [40.750354, nil] assert !p.geocoded? end def test_distance_to_returns_float p = PlaceUsingMongoid.new(*geocoded_object_params(:msg)) p.location = [40.750354, -73.993371] assert p.distance_to([30, -94]).is_a?(Float) end def test_model_configuration p = PlaceUsingMongoid.new(*geocoded_object_params(:msg)) p.location = [0, 0] PlaceUsingMongoid.geocoded_by :address, :coordinates => :location, :units => :km assert_equal 111, p.distance_to([0,1]).round PlaceUsingMongoid.geocoded_by :address, :coordinates => :location, :units => :mi assert_equal 69, p.distance_to([0,1]).round end def test_index_is_skipped_if_skip_option_flag if PlaceUsingMongoidWithoutIndex.respond_to?(:index_options) result = PlaceUsingMongoidWithoutIndex.index_options.keys.flatten[0] == :coordinates else result = PlaceUsingMongoidWithoutIndex.index_specifications[0] == :coordinates end assert !result end def test_geocoded_with_custom_handling p = PlaceUsingMongoidWithCustomResultsHandling.new(*geocoded_object_params(:msg)) p.location = [40.750354, -73.993371] p.geocode assert_match(/[0-9\.,\-]+/, p.coords_string) end def test_reverse_geocoded p = PlaceUsingMongoidReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) p.reverse_geocode assert_match(/New York/, p.address) end def test_reverse_geocoded_with_custom_handling p = PlaceUsingMongoidReverseGeocodedWithCustomResultsHandling.new(*reverse_geocoded_object_params(:msg)) p.reverse_geocode assert_equal "US", p.country.upcase end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookup_test.rb
test/unit/lookup_test.rb
# encoding: utf-8 require 'test_helper' class LookupTest < GeocoderTestCase def test_responds_to_name_method Geocoder::Lookup.all_services.each do |l| lookup = Geocoder::Lookup.get(l) assert lookup.respond_to?(:name), "Lookup #{l} does not respond to #name method." end end def test_search_returns_empty_array_when_no_results Geocoder::Lookup.all_services_except_test.each do |l| next if [ :abstract_api, :ipgeolocation, :ipqualityscore, :melissa_street, :nationaal_georegister_nl, :twogis ].include?(l) # lookups that always return a result lookup = Geocoder::Lookup.get(l) set_api_key!(l) silence_warnings do assert_equal [], lookup.send(:results, Geocoder::Query.new("no results")), "Lookup #{l} does not return empty array when no results." end end end def test_query_url_contains_values_in_params_hash Geocoder::Lookup.all_services_except_test.each do |l| next if [:freegeoip, :maxmind_local, :telize, :pointpin, :geoip2, :maxmind_geoip2, :mapbox, :ipdata_co, :ipinfo_io, :ipinfo_io_lite, :ipapi_com, :ipregistry, :ipstack, :postcodes_io, :uk_ordnance_survey_names, :amazon_location_service, :ipbase, :ip2location_lite].include? l # does not use query string set_api_key!(l) url = Geocoder::Lookup.get(l).query_url(Geocoder::Query.new( "test", :params => {:one_in_the_hand => "two in the bush"} )) assert_match(/one_in_the_hand=two\+in\+the\+bush/, url, "Lookup #{l} does not appear to support arbitrary params in URL") end end { :esri => :l, :bing => :key, :geocoder_ca => :auth, :google => :language, :google_premier => :language, :mapquest => :key, :maxmind => :l, :nominatim => :"accept-language", :yandex => :lang, :pc_miler => :region }.each do |l,p| define_method "test_passing_param_to_#{l}_query_overrides_configuration_value" do set_api_key!(l) url = Geocoder::Lookup.get(l).query_url(Geocoder::Query.new( "test", :params => {p => "xxxx"} )) assert_match(/#{p}=xxxx/, url, "Param passed to #{l} lookup does not override configuration value") end end { :bing => :culture, :google => :language, :google_premier => :language, :here => :lang, :nominatim => :"accept-language", :yandex => :lang }.each do |l,p| define_method "test_passing_language_to_#{l}_query_overrides_configuration_value" do set_api_key!(l) url = Geocoder::Lookup.get(l).query_url(Geocoder::Query.new( "test", :language => 'xxxx' )) assert_match(/#{p}=xxxx/, url, "Param passed to #{l} lookup does not override configuration value") end end def test_raises_exception_on_invalid_key Geocoder.configure(:always_raise => [Geocoder::InvalidApiKey]) #Geocoder::Lookup.all_services_except_test.each do |l| [:bing, :yandex, :maxmind, :baidu, :baidu_ip, :amap].each do |l| lookup = Geocoder::Lookup.get(l) assert_raises Geocoder::InvalidApiKey do lookup.send(:results, Geocoder::Query.new("invalid key")) end end end def test_returns_empty_array_on_invalid_key silence_warnings do #Geocoder::Lookup.all_services_except_test.each do |l| [:bing, :yandex, :maxmind, :baidu, :baidu_ip, :amap, :pc_miler].each do |l| Geocoder.configure(:lookup => l) set_api_key!(l) assert_equal [], Geocoder.search("invalid key") end end end def test_does_not_choke_on_nil_address Geocoder::Lookup.all_services.each do |l| Geocoder.configure(:lookup => l) assert_nothing_raised { Place.new("Place", nil).geocode } end end def test_hash_to_query g = Geocoder::Lookup::Google.new assert_equal "a=1&b=2", g.send(:hash_to_query, {:a => 1, :b => 2}) end def test_baidu_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::BaiduIp.new assert_match "ak=MY_KEY", g.query_url(Geocoder::Query.new("232.65.123.94")) end def test_baidu_ip_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::Baidu.new assert_match "ak=MY_KEY", g.query_url(Geocoder::Query.new("Madison Square Garden, New York, NY 10001, United States")) end def test_db_ip_com_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::DbIpCom.new assert_match "\/MY_KEY\/", g.query_url(Geocoder::Query.new("232.65.123.94")) end def test_pointpin_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::Pointpin.new assert_match "/MY_KEY/", g.query_url(Geocoder::Query.new("232.65.123.94")) end def test_google_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::Google.new assert_match "key=MY_KEY", g.query_url(Geocoder::Query.new("Madison Square Garden, New York, NY 10001, United States")) end def test_geocoder_ca_showpostal Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::GeocoderCa.new assert_match "showpostal=1", g.query_url(Geocoder::Query.new("Madison Square Garden, New York, NY 10001, United States")) end def test_telize_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::Telize.new assert_match "rapidapi-key=MY_KEY", g.query_url(Geocoder::Query.new("232.65.123.94")) end def test_ipinfo_io_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::IpinfoIo.new assert_match "token=MY_KEY", g.query_url(Geocoder::Query.new("232.65.123.94")) end def test_ipregistry_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::Ipregistry.new assert_match "key=MY_KEY", g.query_url(Geocoder::Query.new("232.65.123.94")) end def test_amap_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::Amap.new assert_match "key=MY_KEY", g.query_url(Geocoder::Query.new("202.198.16.3")) end def test_raises_configuration_error_on_missing_key [:bing, :baidu, :amap].each do |l| assert_raises Geocoder::ConfigurationError do Geocoder.configure(:lookup => l, :api_key => nil) Geocoder.search("Madison Square Garden, New York, NY 10001, United States") end end end def test_lookup_requires_lookup_file_when_class_name_shadowed_by_existing_constant Geocoder::Lookup.street_services << :mock_lookup assert_raises LoadError do Geocoder.configure(:lookup => :mock_lookup, :api_key => "MY_KEY") Geocoder.search("Madison Square Garden, New York, NY 10001, United States") end Geocoder::Lookup.street_services.reject! { |service| service == :mock_lookup } end def test_handle assert_equal :google, Geocoder::Lookup::Google.new.handle assert_equal :geocoder_ca, Geocoder::Lookup::GeocoderCa.new.handle end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/model_test.rb
test/unit/model_test.rb
# encoding: utf-8 require 'test_helper' class ModelTest < GeocoderTestCase def test_geocode_with_block_runs_block e = PlaceWithCustomResultsHandling.new(*geocoded_object_params(:msg)) e.geocode assert_match(/[0-9\.,\-]+/, e.coords_string) end def test_geocode_with_block_doesnt_auto_assign_coordinates e = PlaceWithCustomResultsHandling.new(*geocoded_object_params(:msg)) e.geocode assert_nil e.latitude assert_nil e.longitude end def test_reverse_geocode_with_block_runs_block e = PlaceReverseGeocodedWithCustomResultsHandling.new(*reverse_geocoded_object_params(:msg)) e.reverse_geocode assert_equal "US", e.country.upcase end def test_reverse_geocode_with_block_doesnt_auto_assign_address e = PlaceReverseGeocodedWithCustomResultsHandling.new(*reverse_geocoded_object_params(:msg)) e.reverse_geocode assert_nil e.address end def test_units_and_method PlaceReverseGeocoded.reverse_geocoded_by :latitude, :longitude, method: :spherical, units: :km assert_equal :km, PlaceReverseGeocoded.geocoder_options[:units] assert_equal :spherical, PlaceReverseGeocoded.geocoder_options[:method] end def test_params params = {incude: "cios2"} PlaceReverseGeocoded.reverse_geocoded_by :latitude, :longitude, params: params assert_equal params, PlaceReverseGeocoded.geocoder_options[:params] end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/proxy_test.rb
test/unit/proxy_test.rb
# encoding: utf-8 require 'test_helper' class ProxyTest < GeocoderTestCase def test_uses_proxy_when_specified Geocoder.configure(:http_proxy => 'localhost') Geocoder.configure(:use_https => false) lookup = Geocoder::Lookup::Bing.new assert lookup.send(:http_client).proxy_class? end def test_doesnt_use_proxy_when_not_specified lookup = Geocoder::Lookup::Bing.new assert !lookup.send(:http_client).proxy_class? end def test_exception_raised_on_bad_proxy_url Geocoder.configure(:http_proxy => ' \\_O< Quack Quack') Geocoder.configure(:use_https => false) assert_raise Geocoder::ConfigurationError do Geocoder::Lookup::Bing.new.send(:http_client) end end def test_accepts_proxy_with_http_protocol Geocoder.configure(:http_proxy => 'http://localhost') Geocoder.configure(:use_https => false) lookup = Geocoder::Lookup::Bing.new assert lookup.send(:http_client).proxy_class? end def test_accepts_proxy_with_https_protocol Geocoder.configure(:https_proxy => 'https://localhost') Geocoder.configure(:use_https => true) lookup = Geocoder::Lookup::Google.new assert lookup.send(:http_client).proxy_class? end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/request_test.rb
test/unit/request_test.rb
# encoding: utf-8 require 'test_helper' class RequestTest < GeocoderTestCase class MockRequest < Rack::Request include Geocoder::Request def initialize(headers={}, ip="") super_env = headers super_env.merge!({'REMOTE_ADDR' => ip}) unless ip == "" super(super_env) end end def setup Geocoder.configure(ip_lookup: :freegeoip) end def test_http_x_real_ip req = MockRequest.new({"HTTP_X_REAL_IP" => "74.200.247.59"}) assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_http_x_client_ip req = MockRequest.new({"HTTP_X_CLIENT_IP" => "74.200.247.59"}) assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_http_x_cluster_client_ip req = MockRequest.new({"HTTP_X_CLUSTER_CLIENT_IP" => "74.200.247.59"}) assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_http_x_forwarded_for_without_proxy req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => "74.200.247.59"}) assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_http_x_forwarded_for_with_proxy req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => "74.200.247.59, 74.200.247.60"}) assert req.geocoder_spoofable_ip == '74.200.247.59' assert req.ip == '74.200.247.60' assert req.location.is_a?(Geocoder::Result::Freegeoip) assert_equal "US", req.location.country_code end def test_safe_http_x_forwarded_for_with_proxy req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => "74.200.247.59, 74.200.247.60"}) assert req.geocoder_spoofable_ip == '74.200.247.59' assert req.ip == '74.200.247.60' assert req.safe_location.is_a?(Geocoder::Result::Freegeoip) assert_equal "MX", req.safe_location.country_code end def test_with_request_ip req = MockRequest.new({}, "74.200.247.59") assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_with_loopback_x_forwarded_for req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => "127.0.0.1"}, "74.200.247.59") assert_equal "US", req.location.country_code end def test_with_private_x_forwarded_for req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => "172.19.0.1"}, "74.200.247.59") assert_equal "US", req.location.country_code end def test_http_x_forwarded_for_with_misconfigured_proxies req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => ","}, "74.200.247.59") assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_non_ip_in_proxy_header req = MockRequest.new({"HTTP_X_FORWARDED_FOR" => "Albequerque NM"}) assert req.location.is_a?(Geocoder::Result::Freegeoip) end def test_safe_location_after_location req = MockRequest.new({"HTTP_X_REAL_IP" => "74.200.247.59"}, "127.0.0.1") assert_equal 'US', req.location.country_code assert_equal 'RD', req.safe_location.country_code end def test_location_after_safe_location req = MockRequest.new({'HTTP_X_REAL_IP' => '74.200.247.59'}, '127.0.0.1') assert_equal 'RD', req.safe_location.country_code assert_equal 'US', req.location.country_code end def test_geocoder_remove_port_from_addresses_with_port expected_ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3'] ips = ['127.0.0.1:3000', '127.0.0.2:8080', '127.0.0.3:9292'] req = MockRequest.new() assert_equal expected_ips, req.send(:geocoder_remove_port_from_addresses, ips) end def test_geocoder_remove_port_from_ipv6_addresses_with_port expected_ips = ['2600:1008:b16e:26da:ecb3:22f7:6be4:2137', '2600:1901:0:2df5::', '2001:db8:1f70::999:de8:7648:6e8', '10.128.0.2'] ips = ['2600:1008:b16e:26da:ecb3:22f7:6be4:2137', '2600:1901:0:2df5::', '[2001:db8:1f70::999:de8:7648:6e8]:100', '10.128.0.2'] req = MockRequest.new() assert_equal expected_ips, req.send(:geocoder_remove_port_from_addresses, ips) end def test_geocoder_remove_port_from_addresses_without_port expected_ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3'] ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3'] req = MockRequest.new() assert_equal expected_ips, req.send(:geocoder_remove_port_from_addresses, ips) end def test_geocoder_reject_non_ipv4_addresses_with_good_ips expected_ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3'] ips = ['127.0.0.1', '127.0.0.2', '127.0.0.3'] req = MockRequest.new() assert_equal expected_ips, req.send(:geocoder_reject_non_ipv4_addresses, ips) end def test_geocoder_reject_non_ipv4_addresses_with_bad_ips expected_ips = ['127.0.0.1'] ips = ['127.0.0', '127.0.0.1', '127.0.0.2.0'] req = MockRequest.new() assert_equal expected_ips, req.send(:geocoder_reject_non_ipv4_addresses, ips) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/util_test.rb
test/unit/util_test.rb
# frozen_string_literal: true require 'test_helper' class UtilTest < GeocoderTestCase def test_recursive_hash_merge h1 = { 'a' => 100, 'b' => 200, 'c' => { 'c1' => 12, 'c2' => 14 } } h2 = { 'b' => 254, 'c' => { 'c1' => 16, 'c3' => 94 } } Geocoder::Util.recursive_hash_merge(h1, h2) assert h1 == { 'a' => 100, 'b' => 254, 'c' => { 'c1' => 16, 'c2' => 14, 'c3' => 94 } } end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/calculations_test.rb
test/unit/calculations_test.rb
# encoding: utf-8 require 'test_helper' class CalculationsTest < GeocoderTestCase def setup Geocoder.configure( :units => :mi, :distances => :linear ) end # --- degree distance --- def test_longitude_degree_distance_at_equator assert_equal 69, Geocoder::Calculations.longitude_degree_distance(0).round end def test_longitude_degree_distance_at_new_york assert_equal 53, Geocoder::Calculations.longitude_degree_distance(40).round end def test_longitude_degree_distance_at_north_pole assert_equal 0, Geocoder::Calculations.longitude_degree_distance(89.98).round end # --- distance between --- def test_distance_between_in_miles assert_equal 69, Geocoder::Calculations.distance_between([0,0], [0,1]).round la_to_ny = Geocoder::Calculations.distance_between([34.05,-118.25], [40.72,-74]).round assert (la_to_ny - 2444).abs < 10 end def test_distance_between_in_kilometers assert_equal 111, Geocoder::Calculations.distance_between([0,0], [0,1], :units => :km).round la_to_ny = Geocoder::Calculations.distance_between([34.05,-118.25], [40.72,-74], :units => :km).round assert (la_to_ny - 3942).abs < 10 end def test_distance_between_in_nautical_miles assert_equal 60, Geocoder::Calculations.distance_between([0,0], [0,1], :units => :nm).round la_to_ny = Geocoder::Calculations.distance_between([34.05,-118.25], [40.72,-74], :units => :nm).round assert (la_to_ny - 2124).abs < 10 end # --- geographic center --- def test_geographic_center_with_arrays assert_equal [0.0, 0.5], Geocoder::Calculations.geographic_center([[0,0], [0,1]]) assert_equal [0.0, 1.0], Geocoder::Calculations.geographic_center([[0,0], [0,1], [0,2]]) end def test_geographic_center_with_mixed_arguments p1 = [0, 0] p2 = PlaceReverseGeocoded.new("Some Cold Place", 0, 1) assert_equal [0.0, 0.5], Geocoder::Calculations.geographic_center([p1, p2]) end # --- bounding box --- def test_bounding_box_calculation_in_miles center = [51, 7] # Cologne, DE radius = 10 # miles corners = [50.86, 6.77, 51.14, 7.23] assert_equal corners.map{ |i| (i * 100).round }, Geocoder::Calculations.bounding_box(center, radius).map{ |i| (i * 100).round } end def test_bounding_box_calculation_in_kilometers center = [51, 7] # Cologne, DE radius = 111 # kilometers (= 1 degree latitude) corners = [50, 5.41, 52, 8.59] assert_equal corners.map{ |i| (i * 100).round }, Geocoder::Calculations.bounding_box(center, radius, :units => :km).map{ |i| (i * 100).round } end def test_bounding_box_calculation_with_object center = [51, 7] # Cologne, DE radius = 10 # miles corners = [50.86, 6.77, 51.14, 7.23] obj = PlaceReverseGeocoded.new("Cologne", center[0], center[1]) assert_equal corners.map{ |i| (i * 100).round }, Geocoder::Calculations.bounding_box(obj, radius).map{ |i| (i * 100).round } end def test_bounding_box_calculation_with_address_string assert_nothing_raised do Geocoder::Calculations.bounding_box("4893 Clay St, San Francisco, CA", 50) end end # --- random point --- def test_random_point_within_radius 20.times do center = [51, 7] # Cologne, DE radius = 10 # miles random_point = Geocoder::Calculations.random_point_near(center, radius) distance = Geocoder::Calculations.distance_between(center, random_point) assert distance <= radius end end # --- bearing --- def test_compass_points assert_equal "N", Geocoder::Calculations.compass_point(0) assert_equal "N", Geocoder::Calculations.compass_point(1.0) assert_equal "N", Geocoder::Calculations.compass_point(360) assert_equal "N", Geocoder::Calculations.compass_point(361) assert_equal "N", Geocoder::Calculations.compass_point(-22) assert_equal "NW", Geocoder::Calculations.compass_point(-23) assert_equal "S", Geocoder::Calculations.compass_point(180) assert_equal "S", Geocoder::Calculations.compass_point(181) end def test_bearing_between bearings = { :n => 0, :e => 90, :s => 180, :w => 270 } points = { :n => [41, -75], :e => [40, -74], :s => [39, -75], :w => [40, -76] } directions = [:n, :e, :s, :w] methods = [:linear, :spherical] methods.each do |m| directions.each_with_index do |d,i| opp = directions[(i + 2) % 4] # opposite direction b = Geocoder::Calculations.bearing_between( points[d], points[opp], :method => m) assert (b - bearings[opp]).abs < 1, "Bearing (#{m}) should be close to #{bearings[opp]} but was #{b}." end end end def test_spherical_bearing_to l = PlaceReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) assert_equal 324, l.bearing_to([50,-85], :method => :spherical).round end def test_spherical_bearing_from l = PlaceReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) assert_equal 136, l.bearing_from([50,-85], :method => :spherical).round end def test_linear_bearing_from_and_to_are_exactly_opposite l = PlaceReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) assert_equal l.bearing_from([50,-86.1]), l.bearing_to([50,-86.1]) - 180 end def test_extract_coordinates_when_integers coords = [-23, 47] l = PlaceReverseGeocoded.new("Madagascar", coords[0], coords[1]) assert_equal coords.map(&:to_f), Geocoder::Calculations.extract_coordinates(l) assert_equal coords.map(&:to_f), Geocoder::Calculations.extract_coordinates(coords) end def test_extract_coordinates_when_strings coords = ["-23.1", "47.2"] l = PlaceReverseGeocoded.new("Madagascar", coords[0], coords[1]) assert_equal coords.map(&:to_f), Geocoder::Calculations.extract_coordinates(l) assert_equal coords.map(&:to_f), Geocoder::Calculations.extract_coordinates(coords) end def test_extract_coordinates_when_nan result = Geocoder::Calculations.extract_coordinates([ nil, nil ]) assert_nan_coordinates?(result) result = Geocoder::Calculations.extract_coordinates(nil) assert_nan_coordinates?(result) result = Geocoder::Calculations.extract_coordinates('') assert_nan_coordinates?(result) result = Geocoder::Calculations.extract_coordinates([ 'nix' ]) assert_nan_coordinates?(result) o = Object.new result = Geocoder::Calculations.extract_coordinates(o) assert_nan_coordinates?(result) end def test_coordinates_present assert Geocoder::Calculations.coordinates_present?(3.23) assert !Geocoder::Calculations.coordinates_present?(nil) assert !Geocoder::Calculations.coordinates_present?(Geocoder::Calculations::NAN) assert !Geocoder::Calculations.coordinates_present?(3.23, nil) end private # ------------------------------------------------------------------ def assert_nan_coordinates?(value) assert value.is_a?(Array) && value.size == 2 && value[0].nan? && value[1].nan?, "Expected value to be [NaN, NaN] but was #{value}" end def test_endpoint # test 5 time with random coordinates and headings [0..5].each do |i| rheading = [*0..359].sample rdistance = [*0..100].sample startpoint = [45.0906, 7.6596] endpoint = Geocoder::Calculations.endpoint(startpoint, rheading, rdistance) assert_in_delta rdistance, Geocoder::Calculations.distance_between(startpoint, endpoint, :method => :spherical), 1E-5 assert_in_delta rheading, Geocoder::Calculations.bearing_between(startpoint, endpoint, :method => :spherical), 1E-2 end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/query_test.rb
test/unit/query_test.rb
# encoding: utf-8 require 'test_helper' class QueryTest < GeocoderTestCase def test_detect_ipv4 assert Geocoder::Query.new("232.65.123.94").ip_address? ip = IPAddr.new("232.65.123.94") assert Geocoder::Query.new(ip).ip_address? end def test_detect_ipv6 assert Geocoder::Query.new("3ffe:0b00:0000:0000:0001:0000:0000:000a").ip_address? ip = IPAddr.new("3ffe:0b00:0000:0000:0001:0000:0000:000a") assert Geocoder::Query.new(ip).ip_address? end def test_detect_non_ip_address assert !Geocoder::Query.new("232.65.123.94.43").ip_address? assert !Geocoder::Query.new("::ffff:123.456.789").ip_address? end def test_strip_trailing_whitespace_for_ip_address_query text = "77.251.213.1\n" query = Geocoder::Query.new(text) assert_equal text[0...-1], query.sanitized_text end def test_blank_query_detection assert Geocoder::Query.new(nil).blank? assert Geocoder::Query.new("").blank? assert Geocoder::Query.new("\t ").blank? assert !Geocoder::Query.new("a").blank? assert !Geocoder::Query.new("Москва").blank? # no ASCII characters assert !Geocoder::Query.new("\na").blank? assert Geocoder::Query.new(nil, :params => {}).blank? assert !Geocoder::Query.new(nil, :params => {:woeid => 1234567}).blank? end def test_blank_query_detection_for_coordinates assert Geocoder::Query.new([nil,nil]).blank? assert Geocoder::Query.new([87,nil]).blank? end def test_coordinates_detection assert Geocoder::Query.new("51.178844,5").coordinates? assert Geocoder::Query.new("51.178844, -1.826189").coordinates? assert !Geocoder::Query.new("232.65.123").coordinates? assert !Geocoder::Query.new("Test\n51.178844, -1.826189").coordinates? end def test_internal_ip_address assert Geocoder::Query.new("127.0.0.1").internal_ip_address? assert Geocoder::Query.new("172.19.0.1").internal_ip_address? assert Geocoder::Query.new("10.100.100.1").internal_ip_address? assert Geocoder::Query.new("192.168.0.1").internal_ip_address? assert !Geocoder::Query.new("232.65.123.234").internal_ip_address? end def test_loopback_ip_address assert Geocoder::Query.new("127.0.0.1").loopback_ip_address? assert !Geocoder::Query.new("232.65.123.234").loopback_ip_address? end def test_private_ip_address assert Geocoder::Query.new("172.19.0.1").private_ip_address? assert Geocoder::Query.new("10.100.100.1").private_ip_address? assert Geocoder::Query.new("192.168.0.1").private_ip_address? assert !Geocoder::Query.new("127.0.0.1").private_ip_address? assert !Geocoder::Query.new("232.65.123.234").private_ip_address? end def test_sanitized_text_with_array q = Geocoder::Query.new([43.1313,11.3131]) assert_equal "43.1313,11.3131", q.sanitized_text end def test_custom_lookup query = Geocoder::Query.new("address", :lookup => :nominatim) assert_instance_of Geocoder::Lookup::Nominatim, query.lookup end def test_force_specify_ip_address Geocoder.configure({:ip_lookup => :google}) query = Geocoder::Query.new("address", {:ip_address => true}) assert !query.ip_address? assert_instance_of Geocoder::Lookup::Google, query.lookup end def test_force_specify_street_address Geocoder.configure({:lookup => :google, :ip_lookup => :freegeoip}) query = Geocoder::Query.new("4.1.0.2", {street_address: true}) assert query.ip_address? assert_instance_of Geocoder::Lookup::Google, query.lookup end def test_force_specify_ip_address_with_ip_lookup query = Geocoder::Query.new("address", {:ip_address => true, :ip_lookup => :google}) assert !query.ip_address? assert_instance_of Geocoder::Lookup::Google, query.lookup end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/configuration_test.rb
test/unit/configuration_test.rb
# encoding: utf-8 require 'test_helper' class ConfigurationTest < GeocoderTestCase def setup Geocoder::Configuration.set_defaults end def test_exception_raised_on_bad_lookup_config Geocoder.configure(:lookup => :stoopid) assert_raises Geocoder::ConfigurationError do Geocoder.search "something dumb" end end def test_setting_with_class_method Geocoder::Configuration.units = :test assert_equal :test, Geocoder.config.units end def test_setting_with_configure_method Geocoder.configure(:units => :test) assert_equal :test, Geocoder.config.units end def test_config_for_lookup Geocoder.configure( :timeout => 5, :api_key => "aaa", :google => { :timeout => 2 } ) assert_equal 2, Geocoder.config_for_lookup(:google).timeout assert_equal "aaa", Geocoder.config_for_lookup(:google).api_key end def test_configuration_chain v = PlaceReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) v.latitude = 0 v.longitude = 0 # method option > global configuration Geocoder.configure(:units => :km) assert_equal 69, v.distance_to([0,1], :mi).round # per-model configuration > global configuration PlaceReverseGeocoded.reverse_geocoded_by :latitude, :longitude, method: :spherical, units: :mi assert_equal 69, v.distance_to([0,1]).round # method option > per-model configuration assert_equal 111, v.distance_to([0,1], :km).round end def test_merge_into_lookup_config base = { timeout: 5, api_key: "xxx" } new = { timeout: 10, units: :km, } merged = { timeout: 10, # overwritten units: :km, # added api_key: "xxx" # preserved } Geocoder.configure(google: base) Geocoder.merge_into_lookup_config(:google, new) assert_equal merged, Geocoder.config[:google] end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/near_test.rb
test/unit/near_test.rb
# encoding: utf-8 require 'test_helper' require 'arel' class NearTest < GeocoderTestCase def test_near_scope_options_includes_bounding_box_condition omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = PlaceWithCustomResultsHandling.send(:near_scope_options, 1.0, 2.0, 5) table_name = PlaceWithCustomResultsHandling.table_name assert_match(/#{table_name}.latitude BETWEEN 0.9276\d* AND 1.0723\d* AND #{table_name}.longitude BETWEEN 1.9276\d* AND 2.0723\d* AND /, result[:conditions][0]) end def test_near_scope_options_includes_radius_condition omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = Place.send(:near_scope_options, 1.0, 2.0, 5) assert_match(/BETWEEN \? AND \?$/, result[:conditions][0]) end def test_near_scope_options_includes_radius_column_max_radius omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = Place.send(:near_scope_options, 1.0, 2.0, :radius_column) assert_match(/BETWEEN \? AND radius_column$/, result[:conditions][0]) end def test_near_scope_options_includes_radius_column_max_radius_arel omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = Place.send(:near_scope_options, 1.0, 2.0, Arel.sql('CASE WHEN TRUE THEN radius_column ELSE 0 END')) assert_match(/BETWEEN \? AND CASE WHEN TRUE THEN radius_column ELSE 0 END$/, result[:conditions][0]) end def test_near_scope_options_includes_radius_default_min_radius omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = Place.send(:near_scope_options, 1.0, 2.0, 5) assert_equal(0, result[:conditions][1]) assert_equal(5, result[:conditions][2]) end def test_near_scope_options_includes_radius_custom_min_radius omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = Place.send(:near_scope_options, 1.0, 2.0, 5, :min_radius => 3) assert_equal(3, result[:conditions][1]) assert_equal(5, result[:conditions][2]) end def test_near_scope_options_includes_radius_bogus_min_radius omit("Not applicable to unextended SQLite") if using_unextended_sqlite? result = Place.send(:near_scope_options, 1.0, 2.0, 5, :min_radius => 'bogus') assert_equal(0, result[:conditions][1]) assert_equal(5, result[:conditions][2]) end def test_near_scope_options_with_defaults result = PlaceWithCustomResultsHandling.send(:near_scope_options, 1.0, 2.0, 5) assert_match(/AS distance/, result[:select]) assert_match(/AS bearing/, result[:select]) assert_no_consecutive_comma(result[:select]) end def test_near_scope_options_with_no_distance result = PlaceWithCustomResultsHandling.send(:near_scope_options, 1.0, 2.0, 5, :select_distance => false) assert_no_match(/AS distance/, result[:select]) assert_match(/AS bearing/, result[:select]) assert_no_match(/distance/, result[:condition]) assert_no_match(/distance/, result[:order]) assert_no_consecutive_comma(result[:select]) end def test_near_scope_options_with_no_bearing result = PlaceWithCustomResultsHandling.send(:near_scope_options, 1.0, 2.0, 5, :select_bearing => false) assert_match(/AS distance/, result[:select]) assert_no_match(/AS bearing/, result[:select]) assert_no_consecutive_comma(result[:select]) end def test_near_scope_options_with_custom_distance_column result = PlaceWithCustomResultsHandling.send(:near_scope_options, 1.0, 2.0, 5, :distance_column => 'calculated_distance') assert_no_match(/AS distance/, result[:select]) assert_match(/AS calculated_distance/, result[:select]) assert_no_match(/\bdistance\b/, result[:order]) assert_match(/calculated_distance/, result[:order]) assert_no_consecutive_comma(result[:select]) end def test_near_scope_options_with_custom_bearing_column result = PlaceWithCustomResultsHandling.send(:near_scope_options, 1.0, 2.0, 5, :bearing_column => 'calculated_bearing') assert_no_match(/AS bearing/, result[:select]) assert_match(/AS calculated_bearing/, result[:select]) assert_no_consecutive_comma(result[:select]) end private def assert_no_consecutive_comma(string) assert_no_match(/, *,/, string, "two consecutive commas") end def using_unextended_sqlite? ENV['DB'] == 'sqlite' && ENV['USE_SQLITE_EXT'] != '1' end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/result_test.rb
test/unit/result_test.rb
# encoding: utf-8 require 'test_helper' class ResultTest < GeocoderTestCase def test_forward_geocoding_result_has_required_attributes Geocoder::Lookup.all_services_except_test.each do |l| next if [ :ip2location, # has pay-per-attribute pricing model :ip2location_io, # has pay-per-attribute pricing model :ip2location_lite, # no forward geocoding :ipinfo_io_lite, # does not support exact location :twogis, # cant find 'Madison Square Garden' ].include?(l) Geocoder.configure(:lookup => l) set_api_key!(l) result = Geocoder.search("Madison Square Garden").first assert_result_has_required_attributes(result) assert_aws_result_supports_place_id(result) if l == :amazon_location_service end end def test_reverse_geocoding_result_has_required_attributes Geocoder::Lookup.all_services_except_test.each do |l| next if [ :ip2location, # has pay-per-attribute pricing model :ip2location_io, # has pay-per-attribute pricing model :ip2location_lite, # no reverse geocoding :ipinfo_io_lite, # no reverse geocoding :nationaal_georegister_nl, # no reverse geocoding :melissa_street, # reverse geocoding not implemented :twogis, # cant find 'Madison Square Garden' ].include?(l) Geocoder.configure(:lookup => l) set_api_key!(l) result = Geocoder.search([45.423733, -75.676333]).first assert_result_has_required_attributes(result) end end private # ------------------------------------------------------------------ def assert_result_has_required_attributes(result) m = "Lookup #{Geocoder.config.lookup} does not support %s attribute." assert result.coordinates.is_a?(Array), m % "coordinates" assert result.latitude.is_a?(Float), m % "latitude" assert result.latitude != 0.0, m % "latitude" assert result.longitude.is_a?(Float), m % "longitude" assert result.longitude != 0.0, m % "longitude" assert result.city.is_a?(String), m % "city" assert result.state.is_a?(String), m % "state" assert result.state_code.is_a?(String), m % "state_code" assert result.province.is_a?(String), m % "province" assert result.province_code.is_a?(String), m % "province_code" assert result.postal_code.is_a?(String), m % "postal_code" assert result.country.is_a?(String), m % "country" assert result.country_code.is_a?(String), m % "country_code" assert_not_nil result.address, m % "address" end def assert_aws_result_supports_place_id(result) assert result.place_id.is_a?(String) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/method_aliases_test.rb
test/unit/method_aliases_test.rb
# encoding: utf-8 require 'test_helper' class MethodAliasesTest < GeocoderTestCase def test_distance_from_is_alias_for_distance_to v = Place.new(*geocoded_object_params(:msg)) v.latitude, v.longitude = [40.750354, -73.993371] assert_equal v.distance_from([30, -94]), v.distance_to([30, -94]) end def test_fetch_coordinates_is_alias_for_geocode v = Place.new(*geocoded_object_params(:msg)) assert_equal [Float, Float], v.fetch_coordinates.map(&:class) end def test_fetch_address_is_alias_for_reverse_geocode v = PlaceReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) assert_match(/New York/, v.fetch_address) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/error_handling_test.rb
test/unit/error_handling_test.rb
# encoding: utf-8 require 'test_helper' class ErrorHandlingTest < GeocoderTestCase def teardown Geocoder.configure(:always_raise => []) end def test_does_not_choke_on_timeout silence_warnings do Geocoder::Lookup.all_services_with_http_requests.each do |l| Geocoder.configure(:lookup => l) set_api_key!(l) assert_nothing_raised { Geocoder.search("timeout") } end end end def test_always_raise_response_parse_error Geocoder.configure(:always_raise => [Geocoder::ResponseParseError]) [:freegeoip, :google, :ipdata_co].each do |l| lookup = Geocoder::Lookup.get(l) set_api_key!(l) assert_raises Geocoder::ResponseParseError do lookup.send(:results, Geocoder::Query.new("invalid_json")) end end end def test_never_raise_response_parse_error [:freegeoip, :google, :ipdata_co].each do |l| lookup = Geocoder::Lookup.get(l) set_api_key!(l) silence_warnings do assert_nothing_raised do lookup.send(:results, Geocoder::Query.new("invalid_json")) end end end end def test_always_raise_timeout_error Geocoder.configure(:always_raise => [Timeout::Error]) Geocoder::Lookup.all_services_with_http_requests.each do |l| lookup = Geocoder::Lookup.get(l) set_api_key!(l) assert_raises Timeout::Error do lookup.send(:results, Geocoder::Query.new("timeout")) end end end def test_always_raise_socket_error Geocoder.configure(:always_raise => [SocketError]) Geocoder::Lookup.all_services_with_http_requests.each do |l| lookup = Geocoder::Lookup.get(l) set_api_key!(l) assert_raises SocketError do lookup.send(:results, Geocoder::Query.new("socket_error")) end end end def test_always_raise_connection_refused_error Geocoder.configure(:always_raise => [Errno::ECONNREFUSED]) Geocoder::Lookup.all_services_with_http_requests.each do |l| lookup = Geocoder::Lookup.get(l) set_api_key!(l) assert_raises Errno::ECONNREFUSED do lookup.send(:results, Geocoder::Query.new("connection_refused")) end end end def test_always_raise_host_unreachable_error Geocoder.configure(:always_raise => [Errno::EHOSTUNREACH]) Geocoder::Lookup.all_services_with_http_requests.each do |l| lookup = Geocoder::Lookup.get(l) set_api_key!(l) assert_raises Errno::EHOSTUNREACH do lookup.send(:results, Geocoder::Query.new("host_unreachable")) end end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/https_test.rb
test/unit/https_test.rb
# encoding: utf-8 require 'test_helper' class HttpsTest < GeocoderTestCase def test_uses_https_for_secure_query Geocoder.configure(:use_https => true) g = Geocoder::Lookup::Google.new assert_match(/^https:/, g.query_url(Geocoder::Query.new("test"))) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/geocoder_test.rb
test/unit/geocoder_test.rb
# encoding: utf-8 require 'test_helper' class GeocoderTest < GeocoderTestCase def test_distance_to_returns_float v = Place.new(*geocoded_object_params(:msg)) v.latitude, v.longitude = [40.750354, -73.993371] assert (v.distance_to([30, -94])).is_a?(Float) end def test_coordinates_method_returns_array assert Geocoder.coordinates("Madison Square Garden, New York, NY").is_a?(Array) end def test_address_method_returns_string assert Geocoder.address([40.750354, -73.993371]).is_a?(String) end def test_geographic_center_doesnt_overwrite_argument_value # test for the presence of a bug that was introduced in version 0.9.11 orig_points = [[52,8], [46,9], [42,5]] points = orig_points.clone Geocoder::Calculations.geographic_center(points) assert_equal orig_points, points end def test_geocode_assigns_and_returns_coordinates v = Place.new(*geocoded_object_params(:msg)) assert_equal [Float, Float], v.geocode.map(&:class) assert_kind_of Numeric, v.latitude assert_kind_of Numeric, v.longitude end def test_geocode_block_executed_when_no_results v = PlaceWithCustomResultsHandling.new("Nowhere", "no results") v.geocode assert_equal "NOT FOUND", v.coords_string end def test_reverse_geocode_assigns_and_returns_address v = PlaceReverseGeocoded.new(*reverse_geocoded_object_params(:msg)) assert_match(/New York/, v.reverse_geocode) assert_match(/New York/, v.address) end def test_forward_and_reverse_geocoding_on_same_model_works g = PlaceWithForwardAndReverseGeocoding.new("Exxon") g.address = "404 New St, Middletown, CT" g.geocode assert_not_nil g.lat assert_not_nil g.lon assert_nil g.location g.reverse_geocode assert_not_nil g.location end def test_geocode_with_custom_lookup_param v = PlaceWithCustomLookup.new(*geocoded_object_params(:msg)) v.geocode assert_equal "Geocoder::Result::Nominatim", v.result_class.to_s end def test_geocode_with_custom_lookup_proc_param v = PlaceWithCustomLookupProc.new(*geocoded_object_params(:msg)) v.geocode assert_equal "Geocoder::Result::Nominatim", v.result_class.to_s end def test_reverse_geocode_with_custom_lookup_param v = PlaceReverseGeocodedWithCustomLookup.new(*reverse_geocoded_object_params(:msg)) v.reverse_geocode assert_equal "Geocoder::Result::Nominatim", v.result_class.to_s end def test_default_geocoder_caching_config assert_nil Geocoder.config[:cache] assert_nil Geocoder.config[:cache_options][:expiration] assert_equal 'geocoder:', Geocoder.config[:cache_options][:prefix] end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/cache_test.rb
test/unit/cache_test.rb
# encoding: utf-8 require 'test_helper' class CacheTest < GeocoderTestCase def setup @tempfile = Tempfile.new("log") @logger = Logger.new(@tempfile.path) Geocoder.configure(logger: @logger) end def teardown Geocoder.configure(logger: :kernel) @logger.close @tempfile.close end def test_second_occurrence_of_request_is_cache_hit Geocoder.configure(:use_https => false) Geocoder.configure(:cache => {}) Geocoder::Lookup.all_services_except_test.each do |l| next if # local, does not use cache l == :maxmind_local || l == :geoip2 || l == :ip2location_lite || # uses the AWS gem, not HTTP requests with caching l == :amazon_location_service Geocoder.configure(:lookup => l) set_api_key!(l) results = Geocoder.search("Madison Square Garden") assert !results.first.cache_hit, "Lookup #{l} returned erroneously cached result." results = Geocoder.search("Madison Square Garden") assert results.first.cache_hit, "Lookup #{l} did not return cached result." end end def test_google_over_query_limit_does_not_hit_cache Geocoder.configure(:cache => {}) Geocoder.configure(:lookup => :google) set_api_key!(:google) Geocoder.configure(:always_raise => :all) assert_raises Geocoder::OverQueryLimitError do Geocoder.search("over limit") end lookup = Geocoder::Lookup.get(:google) assert_equal false, lookup.instance_variable_get(:@cache_hit) assert_raises Geocoder::OverQueryLimitError do Geocoder.search("over limit") end assert_equal false, lookup.instance_variable_get(:@cache_hit) end def test_bing_service_unavailable_without_raising_does_not_hit_cache Geocoder.configure(cache: {}, lookup: :bing, always_raise: []) set_api_key!(:bing) lookup = Geocoder::Lookup.get(:bing) Geocoder.search("service unavailable") assert_false lookup.instance_variable_get(:@cache_hit) Geocoder.search("service unavailable") assert_false lookup.instance_variable_get(:@cache_hit) end def test_expire_all_urls Geocoder.configure(cache: {}, cache_options: {prefix: "geocoder:"}) lookup = Geocoder::Lookup.get(:nominatim) lookup.cache['http://api.nominatim.com/'] = 'data' assert_operator 0, :<, lookup.cache.send(:keys).size lookup.cache.expire(:all) assert_equal 0, lookup.cache.send(:keys).size end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/twogis_test.rb
test/unit/lookups/twogis_test.rb
# encoding: utf-8 require 'test_helper' class TwogisTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :twogis) set_api_key!(:twogis) end def test_twogis_point result = Geocoder.search('Kremlin, Moscow, Russia').first assert_equal [55.755836, 37.617774], result.coordinates end def test_twogis_no_results silence_warnings do results = Geocoder.search("no results") assert_equal 0, results.length end end def test_twogis_no_city result = Geocoder.search('chernoe more').first assert_equal "", result.city end def test_twogis_no_country result = Geocoder.search('new york').first assert_equal "", result.country end def test_twogis_result_kind assert_nothing_raised do ["new york", [55.755836, 37.617774], 'chernoe more'].each do |query| Geocoder.search(query).first.type end end end def test_twogis_result_returns_street_name assert_nothing_raised do result = Geocoder.search("ohotniy riad 2").first assert_equal "улица Охотный Ряд", result.street end end def test_twogis_result_returns_street_address assert_nothing_raised do result = Geocoder.search("ohotniy riad 2").first assert_equal "улица Охотный Ряд, 2", result.street_address end end def test_twogis_result_returns_street_number assert_nothing_raised do result = Geocoder.search("ohotniy riad 2").first assert_equal "2", result.street_number end end def test_twogis_maximum_precision_on_russian_address result = Geocoder.search('ohotniy riad 2').first assert_equal [55.757261, 37.616732], result.coordinates assert_equal "Москва, улица Охотный Ряд, 2", result.address assert_equal "Тверской район", result.district assert_equal "Москва", result.city assert_equal "Москва", result.region assert_equal "Россия", result.country assert_equal "улица Охотный Ряд, 2", result.street_address assert_equal "улица Охотный Ряд", result.street assert_equal "2", result.street_number assert_equal "building", result.type assert_equal "Многофункциональный комплекс", result.purpose_name assert_equal "Four Seasons Moscow, отель", result.building_name end def test_twogis_hydro_object result = Geocoder.search('volga river').first assert_equal [57.953151, 38.388873], result.coordinates assert_equal "", result.address assert_equal "", result.district assert_equal "Некоузский район", result.district_area assert_equal "Россия", result.country assert_equal "Ярославская область", result.region assert_equal "", result.street_address assert_equal "", result.street assert_equal "", result.street_number assert_equal "adm_div", result.type assert_equal "", result.purpose_name assert_equal "", result.building_name assert_equal "settlement", result.subtype assert_equal "Посёлок", result.subtype_specification assert_equal "settlement", result.subtype assert_equal "Волга", result.name end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/pdok_nl_test.rb
test/unit/lookups/pdok_nl_test.rb
# encoding: utf-8 require 'test_helper' class PdokNlTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :pdok_nl) end def test_result_components result = Geocoder.search('Nieuwezijds Voorburgwal 147, Amsterdam').first assert_equal result.street, 'Nieuwezijds Voorburgwal' assert_equal result.street_number, '147' assert_equal result.city, 'Amsterdam' assert_equal result.postal_code, '1012RJ' assert_equal result.address, 'Nieuwezijds Voorburgwal 147, 1012RJ Amsterdam' assert_equal result.province, 'Noord-Holland' assert_equal result.province_code, 'PV27' assert_equal result.country_code, 'NL' assert_equal result.latitude, 52.37316398 assert_equal result.longitude, 4.89089949 end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/google_test.rb
test/unit/lookups/google_test.rb
# encoding: utf-8 require 'test_helper' class GoogleTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :google) end def test_google_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "Manhattan", result.address_components_of_type(:sublocality).first['long_name'] end def test_google_result_components_contains_route result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "Penn Plaza", result.address_components_of_type(:route).first['long_name'] end def test_google_result_components_contains_street_number result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "4", result.address_components_of_type(:street_number).first['long_name'] end def test_google_returns_city_when_no_locality_in_result result = Geocoder.search("no locality").first assert_equal "Haram", result.city end def test_google_city_results_returns_nil_if_no_matching_component_types result = Geocoder.search("no city data").first assert_equal nil, result.city end def test_google_street_address_returns_formatted_street_address result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "4 Penn Plaza", result.street_address end def test_google_precision result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "ROOFTOP", result.precision end def test_google_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.7473324, -73.9965316, 40.7536276, -73.9902364], result.viewport end def test_google_bounds result = Geocoder.search("new york").first assert_equal [40.4773991, -74.2590899, 40.9175771, -73.7002721], result.bounds end def test_google_no_bounds result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal nil, result.bounds end def test_google_query_url_contains_bounds lookup = Geocoder::Lookup::Google.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :bounds => [[40.0, -120.0], [39.0, -121.0]] )) assert_match(/bounds=40.0+%2C-120.0+%7C39.0+%2C-121.0+/, url) end def test_google_query_url_contains_region lookup = Geocoder::Lookup::Google.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :region => "gb" )) assert_match(/region=gb/, url) end def test_google_query_url_contains_components_when_given_as_string lookup = Geocoder::Lookup::Google.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :components => "locality:ES" )) formatted = "components=" + CGI.escape("locality:ES") assert url.include?(formatted), "Expected #{formatted} to be included in #{url}" end def test_google_query_url_contains_components_when_given_as_array lookup = Geocoder::Lookup::Google.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :components => ["country:ES", "locality:ES"] )) formatted = "components=" + CGI.escape("country:ES|locality:ES") assert url.include?(formatted), "Expected #{formatted} to be included in #{url}" end def test_google_query_url_contains_result_type_when_given_as_string lookup = Geocoder::Lookup::Google.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :result_type => "country" )) formatted = "result_type=" + CGI.escape("country") assert url.include?(formatted), "Expected #{formatted} to be included in #{url}" end def test_google_query_url_contains_result_type_when_given_as_array lookup = Geocoder::Lookup::Google.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :result_type => ["country", "postal_code"] )) formatted = "result_type=" + CGI.escape("country|postal_code") assert url.include?(formatted), "Expected #{formatted} to be included in #{url}" end def test_google_uses_https_when_api_key_is_set Geocoder.configure(api_key: "deadbeef") query = Geocoder::Query.new("Madison Square Garden, New York, NY") assert_match(/^https:/, query.url) end def test_actual_make_api_request_with_https Geocoder.configure(use_https: true, lookup: :google) require 'webmock/test_unit' WebMock.enable! stub_all = WebMock.stub_request(:any, /.*/).to_return(status: 200) g = Geocoder::Lookup::Google.new g.send(:actual_make_api_request, Geocoder::Query.new('test location')) assert_requested(stub_all) WebMock.reset! WebMock.disable! end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipinfo_io_lite_test.rb
test/unit/lookups/ipinfo_io_lite_test.rb
require 'test_helper' class IpinfoIoLiteTest < GeocoderTestCase def test_ipinfo_io_lite_lookup_loopback_address Geocoder.configure(ip_lookup: :ipinfo_io_lite) result = Geocoder.search('127.0.0.1').first assert_equal '127.0.0.1', result.ip end def test_ipinfo_io_lite_lookup_private_address Geocoder.configure(ip_lookup: :ipinfo_io_lite) result = Geocoder.search('172.19.0.1').first assert_equal '172.19.0.1', result.ip end def test_ipinfo_io_lite_extra_attributes Geocoder.configure(ip_lookup: :ipinfo_io_lite, use_https: true) result = Geocoder.search('8.8.8.8').first assert_equal '8.8.8.8', result.ip assert_equal 'US', result.country_code assert_equal 'United States', result.country assert_equal 'North America', result.continent assert_equal 'NA', result.continent_code assert_equal 'Google LLC', result.as_name end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/yandex_test.rb
test/unit/lookups/yandex_test.rb
# encoding: utf-8 $: << File.join(File.dirname(__FILE__), "..", "..") require 'test_helper' class YandexTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :yandex, language: :en) end def test_yandex_viewport result = Geocoder.search('Kremlin, Moscow, Russia').first assert_equal [55.748189, 37.612587, 55.755044, 37.623187], result.viewport end def test_yandex_no_country_in_results result = Geocoder.search('black sea').first assert_equal "", result.country_code assert_equal "", result.country end def test_yandex_query_url_contains_bbox lookup = Geocoder::Lookup::Yandex.new url = lookup.query_url(Geocoder::Query.new( "Some Intersection", :bounds => [[40.0, -120.0], [39.0, -121.0]] )) if RUBY_VERSION < '2.5.0' assert_match(/bbox=40.0+%2C-120.0+%7E39.0+%2C-121.0+/, url) else assert_match(/bbox=40.0+%2C-120.0+~39.0+%2C-121.0+/, url) end end def test_yandex_result_without_city_does_not_raise_exception assert_nothing_raised do set_api_key!(:yandex) result = Geocoder.search("no city and town").first assert_equal "", result.city end end def test_yandex_result_without_admin_area_no_exception assert_nothing_raised do set_api_key!(:yandex) result = Geocoder.search("no administrative area").first assert_equal "", result.city end end def test_yandex_result_new_york assert_nothing_raised do set_api_key!(:yandex) result = Geocoder.search("new york").first assert_equal "", result.city end end def test_yandex_result_kind assert_nothing_raised do set_api_key!(:yandex) ["new york", [45.423733, -75.676333], "no city and town"].each do |query| Geocoder.search("new york").first.kind end end end def test_yandex_result_without_locality_name assert_nothing_raised do set_api_key!(:yandex) result = Geocoder.search("canada rue dupuis 14")[6] assert_equal "", result.city end end def test_yandex_result_returns_street_name assert_nothing_raised do set_api_key!(:yandex) result = Geocoder.search("canada rue dupuis 14")[6] assert_equal "Rue Hormidas-Dupuis", result.street end end def test_yandex_result_returns_street_number assert_nothing_raised do set_api_key!(:yandex) result = Geocoder.search("canada rue dupuis 14")[6] assert_equal "14", result.street_number end end def test_yandex_find_in_hash_method result = Geocoder::Result::Yandex.new({}) hash = { 'root_node' => { 'node_1' => [1, 2, 3], 'node_2' => { 'data' => 'foo' } } } assert_equal [1, 2, 3], result.send(:find_in_hash, hash, 'root_node', 'node_1') assert_equal "foo", result.send(:find_in_hash, hash, 'root_node', 'node_2', 'data') assert_equal nil, result.send(:find_in_hash, hash, 'root_node', 'node_3') assert_equal nil, result.send(:find_in_hash, hash, 'root_node', 'node_2', 'another_data') assert_equal nil, result.send(:find_in_hash, hash, 'root_node', 'node_2', 'data', 'x') end def test_yandex_maximum_precision_on_russian_address result = Geocoder.search('putilkovo novotushinskaya 5').first assert_equal [55.872258, 37.403522], result.coordinates assert_equal [55.86995, 37.399416, 55.874567, 37.407627], result.viewport assert_equal "Russia, Moscow Region, gorodskoy okrug Krasnogorsk, " \ "derevnya Putilkovo, Novotushinskaya ulitsa, 5", result.address assert_equal "derevnya Putilkovo", result.city assert_equal "Russia", result.country assert_equal "RU", result.country_code assert_equal "Moscow Region", result.state assert_equal "gorodskoy okrug Krasnogorsk", result.sub_state assert_equal "", result.state_code assert_equal "Novotushinskaya ulitsa", result.street assert_equal "5", result.street_number assert_equal "", result.premise_name assert_equal "143441", result.postal_code assert_equal "house", result.kind assert_equal "exact", result.precision end def test_yandex_hydro_object result = Geocoder.search('volga river').first assert_equal [49.550996, 45.139984], result.coordinates assert_equal [45.697053, 32.468241, 58.194645, 50.181608], result.viewport assert_equal "Russia, Volga River", result.address assert_equal "", result.city assert_equal "Russia", result.country assert_equal "RU", result.country_code assert_equal "", result.state assert_equal "", result.sub_state assert_equal "", result.state_code assert_equal "", result.street assert_equal "", result.street_number assert_equal "Volga River", result.premise_name assert_equal "", result.postal_code assert_equal "hydro", result.kind assert_equal "other", result.precision end def test_yandex_province_object result = Geocoder.search('ontario').first assert_equal [49.294248, -87.170557], result.coordinates assert_equal [41.704494, -95.153382, 56.88699, -74.321387], result.viewport assert_equal "Canada, Ontario", result.address assert_equal "", result.city assert_equal "Canada", result.country assert_equal "CA", result.country_code assert_equal "Ontario", result.state assert_equal "", result.sub_state assert_equal "", result.state_code assert_equal "", result.street assert_equal "", result.street_number assert_equal "", result.premise_name assert_equal "", result.postal_code assert_equal "province", result.kind assert_equal "other", result.precision end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/amazon_location_service_test.rb
test/unit/lookups/amazon_location_service_test.rb
# encoding: utf-8 require 'test_helper' class AmazonLocationServiceTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :amazon_location_service, amazon_location_service: {index_name: "some_index_name"}) end def test_amazon_location_service_geocoding result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "Madison Ave, Staten Island, NY, 10314, USA", result.address assert_equal "Staten Island", result.city assert_equal "New York", result.state end def test_amazon_location_service_reverse_geocoding result = Geocoder.search([45.423733, -75.676333]).first assert_equal "Madison Ave, Staten Island, NY, 10314, USA", result.address assert_equal "Staten Island", result.city assert_equal "New York", result.state end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/bing_test.rb
test/unit/lookups/bing_test.rb
# encoding: utf-8 require 'test_helper' class BingTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :bing) set_api_key!(:bing) end def test_query_for_reverse_geocode lookup = Geocoder::Lookup::Bing.new url = lookup.query_url(Geocoder::Query.new([45.423733, -75.676333])) assert_match(/Locations\/45.423733/, url) end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "Madison Square Garden, NY", result.address assert_equal "NY", result.state assert_equal "New York", result.city end def test_result_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [ 40.744944289326668, -74.002353921532631, 40.755675807595253, -73.983625397086143 ], result.viewport end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_query_url_contains_region lookup = Geocoder::Lookup::Bing.new url = lookup.query_url(Geocoder::Query.new( "manchester", :region => "uk" )) assert_match(%r!Locations/uk/\?q=manchester!, url) end def test_query_url_without_region lookup = Geocoder::Lookup::Bing.new url = lookup.query_url(Geocoder::Query.new( "manchester" )) assert_match(%r!Locations/\?q=manchester!, url) end def test_query_url_escapes_spaces_in_address lookup = Geocoder::Lookup::Bing.new url = lookup.query_url(Geocoder::Query.new( "manchester, lancashire", :region => "uk" )) assert_match(%r!Locations/uk/\?q=manchester%2C%20lancashire!, url) end def test_query_url_strips_trailing_and_leading_spaces lookup = Geocoder::Lookup::Bing.new url = lookup.query_url(Geocoder::Query.new( " manchester, lancashire ", :region => "uk" )) assert_match(%r!Locations/uk/\?q=manchester%2C%20lancashire!, url) end def test_raises_exception_when_service_unavailable Geocoder.configure(:always_raise => [Geocoder::ServiceUnavailable]) l = Geocoder::Lookup.get(:bing) assert_raises Geocoder::ServiceUnavailable do l.send(:results, Geocoder::Query.new("service unavailable")) end end def test_raises_exception_when_bing_returns_forbidden_request Geocoder.configure(:always_raise => [Geocoder::RequestDenied]) assert_raises Geocoder::RequestDenied do Geocoder.search("forbidden request") end end def test_raises_exception_when_bing_returns_internal_server_error Geocoder.configure(:always_raise => [Geocoder::ServiceUnavailable]) assert_raises Geocoder::ServiceUnavailable do Geocoder.search("internal server error") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipdata_co_test.rb
test/unit/lookups/ipdata_co_test.rb
# encoding: utf-8 require 'test_helper' class IpdataCoTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :ipdata_co) end def test_result_on_ip_address_search result = Geocoder.search("74.200.247.59").first assert result.is_a?(Geocoder::Result::IpdataCo) end def test_result_on_loopback_ip_address_search result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal 'RD', result.country_code assert_equal "Reserved", result.country end def test_result_on_private_ip_address_search result = Geocoder.search("172.19.0.1").first assert_equal "172.19.0.1", result.ip assert_equal 'RD', result.country_code assert_equal "Reserved", result.country end def test_invalid_json Geocoder.configure(:always_raise => [Geocoder::ResponseParseError]) assert_raise Geocoder::ResponseParseError do Geocoder.search("8.8.8", ip_address: true) end end def test_result_components result = Geocoder.search("74.200.247.59").first assert_equal "Jersey City, NJ 07302, United States", result.address end def test_not_authorized Geocoder.configure(always_raise: [Geocoder::RequestDenied]) lookup = Geocoder::Lookup.get(:ipdata_co) assert_raises Geocoder::RequestDenied do response = MockHttpResponse.new(code: 403) lookup.send(:check_response_for_errors!, response) end end def test_api_key Geocoder.configure(:api_key => 'XXXX') # HACK: run the code once to add the api key to the HTTP request headers Geocoder.search('8.8.8.8') # It's really hard to 'un-monkey-patch' the base lookup class here require 'webmock/test_unit' WebMock.enable! stubbed_request = WebMock.stub_request(:get, "https://api.ipdata.co/8.8.8.8?api-key=XXXX").to_return(status: 200) g = Geocoder::Lookup::IpdataCo.new g.send(:actual_make_api_request, Geocoder::Query.new('8.8.8.8')) assert_requested(stubbed_request) WebMock.reset! WebMock.disable! end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/esri_test.rb
test/unit/lookups/esri_test.rb
# encoding: utf-8 require 'test_helper' require 'geocoder/esri_token' class EsriTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :esri) end def test_query_for_geocode query = Geocoder::Query.new("Bluffton, SC") lookup = Geocoder::Lookup.get(:esri) res = lookup.query_url(query) assert_equal "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/find?f=pjson&outFields=%2A&text=Bluffton%2C+SC", res end def test_query_for_geocode_with_source_country Geocoder.configure(esri: {source_country: 'USA'}) query = Geocoder::Query.new("Bluffton, SC") lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{sourceCountry=USA}, url end def test_query_for_geocode_with_preferred_label_values Geocoder.configure(esri: {preferred_label_values: 'localCity'}) query = Geocoder::Query.new("Bluffton, SC") lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{preferredLabelValues=localCity}, url end def test_query_for_geocode_with_token_and_for_storage token = Geocoder::EsriToken.new('xxxxx', Time.now + 60*60*24) Geocoder.configure(esri: {token: token, for_storage: true}) query = Geocoder::Query.new("Bluffton, SC") lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{forStorage=true}, url assert_match %r{token=xxxxx}, url end def test_token_from_options options_token = Geocoder::EsriToken.new('options_token', Time.now + 60*60*24) query = Geocoder::Query.new("Bluffton, SC", token: options_token) lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{token=options_token}, url end def test_token_from_options_overrides_configuration config_token = Geocoder::EsriToken.new('config_token', Time.now + 60*60*24) options_token = Geocoder::EsriToken.new('options_token', Time.now + 60*60*24) Geocoder.configure(esri: { token: config_token }) query = Geocoder::Query.new("Bluffton, SC", token: options_token) lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{token=options_token}, url end def test_query_for_geocode_with_config_for_storage_false Geocoder.configure(esri: {for_storage: false}) query = Geocoder::Query.new("Bluffton, SC", for_storage: true) lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{forStorage=true}, url query = Geocoder::Query.new("Bluffton, SC", for_storage: false) lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_no_match %r{forStorage}, url end def test_query_for_geocode_with_config_for_storage_true Geocoder.configure(esri: {for_storage: true}) query = Geocoder::Query.new("Bluffton, SC", for_storage: true) lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_match %r{forStorage=true}, url query = Geocoder::Query.new("Bluffton, SC", for_storage: false) lookup = Geocoder::Lookup.get(:esri) url = lookup.query_url(query) assert_no_match %r{forStorage}, url end def test_token_generation_doesnt_overwrite_existing_config Geocoder.configure(esri: {api_key: ['id','secret'], for_storage: true}) query = Geocoder::Query.new("Bluffton, SC") lookup = Geocoder::Lookup.get(:esri) lookup.instance_eval do # redefine `create_token` to return a manually-created token def create_token "xxxxx" end end url = lookup.query_url(query) assert_match %r{forStorage=true}, url assert_match %r{token=xxxxx}, url end def test_query_for_reverse_geocode query = Geocoder::Query.new([45.423733, -75.676333]) lookup = Geocoder::Lookup.get(:esri) res = lookup.query_url(query) assert_equal "https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?f=pjson&location=-75.676333%2C45.423733&outFields=%2A", res end def test_results_component result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "10001", result.postal_code assert_equal "USA", result.country assert_equal "Madison Square Garden", result.address assert_equal "New York", result.city assert_equal "New York", result.state assert_equal "NY", result.state_code assert_equal "Madison Square Garden", result.place_name assert_equal "Sports Complex", result.place_type assert_equal(40.75004981300049, result.coordinates[0]) assert_equal(-73.99423889799965, result.coordinates[1]) end def test_results_component_when_location_type_is_national_capital result = Geocoder.search("washington dc").first assert_equal "Washington", result.city assert_equal "District of Columbia", result.state assert_equal "DC", result.state_code assert_equal "USA", result.country assert_equal "Washington, D. C., District of Columbia, United States", result.address assert_equal "Washington", result.place_name assert_equal "National Capital", result.place_type assert_equal(38.895107833000452, result.coordinates[0]) assert_equal(-77.036365517999627, result.coordinates[1]) end def test_results_component_when_location_type_is_state_capital result = Geocoder.search("austin tx").first assert_equal "Austin", result.city assert_equal "Texas", result.state assert_equal "TX", result.state_code assert_equal "USA", result.country assert_equal "Austin, Texas, United States", result.address assert_equal "Austin", result.place_name assert_equal "State Capital", result.place_type assert_equal(30.267145960000448, result.coordinates[0]) assert_equal(-97.743055550999657, result.coordinates[1]) end def test_results_component_when_location_type_is_city result = Geocoder.search("new york ny").first assert_equal "New York City", result.city assert_equal "New York", result.state assert_equal "NY", result.state_code assert_equal "USA", result.country assert_equal "New York City, New York, United States", result.address assert_equal "New York City", result.place_name assert_equal "City", result.place_type assert_equal(40.714269404000447, result.coordinates[0]) assert_equal(-74.005969928999662, result.coordinates[1]) end def test_results_component_when_reverse_geocoding result = Geocoder.search([45.423733, -75.676333]).first assert_equal "75007", result.postal_code assert_equal "FRA", result.country assert_equal "4 Avenue Gustave Eiffel", result.address assert_equal "Paris", result.city assert_equal "Île-de-France", result.state assert_equal "Île-de-France", result.state_code assert_equal "4 Avenue Gustave Eiffel", result.place_name assert_equal "Address", result.place_type assert_equal(48.858129997357558, result.coordinates[0]) assert_equal(2.2956200048981574, result.coordinates[1]) end def test_results_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.744050000000001, -74.000241000000003, 40.756050000000002, -73.988241000000002], result.viewport end def test_cache_key_doesnt_include_api_key_or_token token = Geocoder::EsriToken.new('xxxxx', Time.now + 60) Geocoder.configure(esri: {token: token, api_key: "xxxxx", for_storage: true}) query = Geocoder::Query.new("Bluffton, SC") lookup = Geocoder::Lookup.get(:esri) key = lookup.send(:cache_key, query) assert_match %r{forStorage}, key assert_no_match %r{token}, key assert_no_match %r{api_key}, key end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipapi_com_test.rb
test/unit/lookups/ipapi_com_test.rb
# encoding: utf-8 require 'test_helper' class IpapiComTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :ipapi_com) end def test_result_on_ip_address_search result = Geocoder.search("74.200.247.59").first assert result.is_a?(Geocoder::Result::IpapiCom) end def test_result_components result = Geocoder.search("74.200.247.59").first assert_equal "Jersey City, NJ 07302, United States", result.address end def test_all_api_fields result = Geocoder.search("74.200.247.59").first assert_equal("United States", result.country) assert_equal("US", result.country_code) assert_equal("NJ", result.region) assert_equal("New Jersey", result.region_name) assert_equal("Jersey City", result.city) assert_equal("07302", result.zip) assert_equal(40.7209, result.lat) assert_equal(-74.0468, result.lon) assert_equal("America/New_York", result.timezone) assert_equal("DataPipe", result.isp) assert_equal("DataPipe", result.org) assert_equal("AS22576 DataPipe, Inc.", result.as) assert_equal("", result.reverse) assert_equal(false, result.mobile) assert_equal(false, result.proxy) assert_equal("74.200.247.59", result.query) assert_equal("success", result.status) assert_equal(nil, result.message) end def test_loopback result = Geocoder.search("::1").first assert_equal(nil, result.lat) assert_equal(nil, result.lon) assert_equal([nil, nil], result.coordinates) assert_equal(nil, result.reverse) assert_equal("::1", result.query) assert_equal("fail", result.status) end def test_private result = Geocoder.search("172.19.0.1").first assert_equal nil, result.lat assert_equal nil, result.lon assert_equal [nil, nil], result.coordinates assert_equal nil, result.reverse assert_equal "172.19.0.1", result.query assert_equal "fail", result.status end def test_api_key Geocoder.configure(:api_key => "MY_KEY") g = Geocoder::Lookup::IpapiCom.new assert_match "key=MY_KEY", g.query_url(Geocoder::Query.new("74.200.247.59")) end def test_url_with_api_key_and_fields Geocoder.configure(:api_key => "MY_KEY", :ipapi_com => {:fields => "lat,lon,xyz"}) g = Geocoder::Lookup::IpapiCom.new assert_equal "https://pro.ip-api.com/json/74.200.247.59?fields=lat%2Clon%2Cxyz&key=MY_KEY", g.query_url(Geocoder::Query.new("74.200.247.59")) end def test_url_with_fields Geocoder.configure(:ipapi_com => {:fields => "lat,lon"}) g = Geocoder::Lookup::IpapiCom.new assert_equal "http://ip-api.com/json/74.200.247.59?fields=lat%2Clon", g.query_url(Geocoder::Query.new("74.200.247.59")) end def test_url_without_fields g = Geocoder::Lookup::IpapiCom.new assert_equal "http://ip-api.com/json/74.200.247.59", g.query_url(Geocoder::Query.new("74.200.247.59")) end def test_search_with_params g = Geocoder::Lookup::IpapiCom.new q = Geocoder::Query.new("74.200.247.59", :params => {:fields => 'lat,zip'}) assert_equal "http://ip-api.com/json/74.200.247.59?fields=lat%2Czip", g.query_url(q) end def test_use_https_with_api_key Geocoder.configure(:api_key => "MY_KEY", :use_https => true) g = Geocoder::Lookup::IpapiCom.new assert_equal "https://pro.ip-api.com/json/74.200.247.59?key=MY_KEY", g.query_url(Geocoder::Query.new("74.200.247.59")) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipinfo_io_test.rb
test/unit/lookups/ipinfo_io_test.rb
# encoding: utf-8 require 'test_helper' class IpinfoIoTest < GeocoderTestCase def test_ipinfo_io_lookup_loopback_address Geocoder.configure(:ip_lookup => :ipinfo_io) result = Geocoder.search("127.0.0.1").first assert_nil result.latitude assert_nil result.longitude assert_equal "127.0.0.1", result.ip end def test_ipinfo_io_lookup_private_address Geocoder.configure(:ip_lookup => :ipinfo_io) result = Geocoder.search("172.19.0.1").first assert_nil result.latitude assert_nil result.longitude assert_equal "172.19.0.1", result.ip end def test_ipinfo_io_extra_attributes Geocoder.configure(:ip_lookup => :ipinfo_io, :use_https => true) result = Geocoder.search("8.8.8.8").first assert_equal "8.8.8.8", result.ip assert_equal "California", result.region assert_equal "94040", result.postal end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/db_ip_com_test.rb
test/unit/lookups/db_ip_com_test.rb
require 'test_helper' class DbIpComTest < GeocoderTestCase def configure_for_free_api_access Geocoder.configure(ip_lookup: :db_ip_com, db_ip_com: { api_key: 'MY_API_KEY' }) set_api_key!(:db_ip_com) end def configure_for_paid_api_access Geocoder.configure(ip_lookup: :db_ip_com, db_ip_com: { api_key: 'MY_API_KEY', use_https: true }) set_api_key!(:db_ip_com) end def test_no_results configure_for_free_api_access results = Geocoder.search('no results') assert_equal 0, results.length end def test_result_on_ip_address_search configure_for_free_api_access result = Geocoder.search('23.255.240.0').first assert result.is_a?(Geocoder::Result::DbIpCom) end def test_result_components configure_for_free_api_access result = Geocoder.search('23.255.240.0').first assert_equal [37.3861, -122.084], result.coordinates assert_equal 'Mountain View, CA 94043, United States', result.address assert_equal 'Mountain View', result.city assert_equal 'Santa Clara County', result.district assert_equal 'CA', result.state_code assert_equal '94043', result.zip_code assert_equal 'United States', result.country_name assert_equal 'US', result.country_code assert_equal 'North America', result.continent_name assert_equal 'NA', result.continent_code assert_equal 'America/Los_Angeles', result.time_zone assert_equal(-7, result.gmt_offset) assert_equal 'USD', result.currency_code end def test_free_host_config configure_for_free_api_access lookup = Geocoder::Lookup::DbIpCom.new query = Geocoder::Query.new('23.255.240.0') assert_match 'https://api.db-ip.com/v2/MY_API_KEY/23.255.240.0', lookup.query_url(query) end def test_paid_host_config configure_for_paid_api_access lookup = Geocoder::Lookup::DbIpCom.new query = Geocoder::Query.new('23.255.240.0') assert_match 'https://api.db-ip.com/v2/MY_API_KEY/23.255.240.0', lookup.query_url(query) end def test_raises_over_limit_exception Geocoder.configure always_raise: :all assert_raises Geocoder::OverQueryLimitError do Geocoder::Lookup::DbIpCom.new.send(:results, Geocoder::Query.new('quota exceeded')) end end def test_raises_unknown_error Geocoder.configure always_raise: :all assert_raises Geocoder::Error do Geocoder::Lookup::DbIpCom.new.send(:results, Geocoder::Query.new('unknown error')) end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/photon_test.rb
test/unit/lookups/photon_test.rb
# frozen_string_literal: true require 'test_helper' # Test for Photon class PhotonTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :photon) end def test_photon_forward_geocoding_result_properties result = Geocoder.search('Madison Square Garden, New York, NY').first geometry = { type: 'Point', coordinates: [-73.99355027800776, 40.7505247] } bounds = [-73.9944446, 40.751161, -73.9925924, 40.7498531] assert_equal(40.7505247, result.latitude) assert_equal(-73.99355027800776, result.longitude) assert_equal '4 Pennsylvania Plaza', result.street_address assert_equal 'Madison Square Garden, 4 Pennsylvania Plaza, New York, New York, 10001, United States of America', result.address assert_equal '4', result.house_number assert_equal 'Pennsylvania Plaza', result.street assert_equal geometry, result.geometry assert_equal bounds, result.bounds assert_equal :way, result.type assert_equal 138_141_251, result.osm_id assert_equal 'leisure=stadium', result.osm_tag end def test_photon_reverse_geocoding_result_properties result = Geocoder.search([45.423733, -75.676333]).first geometry = { type: 'Point', coordinates: [-73.9935078, 40.750499] } assert_equal(40.750499, result.latitude) assert_equal(-73.9935078, result.longitude) assert_equal '4 Pennsylvania Plaza', result.street_address assert_equal '4 Pennsylvania Plaza, New York, New York, 10121, United States of America', result.address assert_equal '4', result.house_number assert_equal 'Pennsylvania Plaza', result.street assert_equal geometry, result.geometry assert_nil result.bounds assert_equal :node, result.type assert_equal 6_985_936_386, result.osm_id assert_equal 'tourism=attraction', result.osm_tag end def test_photon_query_url_contains_language lookup = Geocoder::Lookup::Photon.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', language: 'de' ) ) assert_match(/lang=de/, url) end def test_photon_query_url_contains_limit lookup = Geocoder::Lookup::Photon.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', limit: 5 ) ) assert_match(/limit=5/, url) end def test_photon_query_url_contains_query lookup = Geocoder::Lookup::Photon.new url = lookup.query_url( Geocoder::Query.new( 'Test Query' ) ) assert_match(/q=Test\+Query/, url) end def test_photon_query_url_contains_params lookup = Geocoder::Lookup::Photon.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', bias: { latitude: 45.423733, longitude: -75.676333, scale: 4 }, filter: { bbox: [-73.9944446, 40.751161, -73.9925924, 40.7498531], osm_tag: 'leisure:stadium' } ) ) assert_match(/q=Test\+Query/, url) assert_match(/lat=45\.423733/, url) assert_match(/lon=-75\.676333/, url) assert_match(/bbox=-73\.9944446%2C40\.751161%2C-73\.9925924%2C40\.7498531/, url) assert_match(/osm_tag=leisure%3Astadium/, url) end def test_photon_reverse_query_url_contains_lat_lon lookup = Geocoder::Lookup::Photon.new url = lookup.query_url( Geocoder::Query.new( [45.423733, -75.676333] ) ) assert_no_match(/q=.*/, url) assert_match(/lat=45\.423733/, url) assert_match(/lon=-75\.676333/, url) end def test_photon_reverse_query_url_contains_params lookup = Geocoder::Lookup::Photon.new url = lookup.query_url( Geocoder::Query.new( [45.423733, -75.676333], radius: 5, distance_sort: true, filter: { string: 'query string filter' } ) ) assert_no_match(/q=.*/, url) assert_match(/lat=45\.423733/, url) assert_match(/lon=-75\.676333/, url) assert_match(/radius=5/, url) assert_match(/distance_sort=true/, url) assert_match(/query_string_filter=query\+string\+filter/, url) end def test_photon_invalid_request Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search('invalid request') end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/google_premier_test.rb
test/unit/lookups/google_premier_test.rb
# encoding: utf-8 require 'test_helper' class GooglePremierTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :google_premier) set_api_key!(:google_premier) end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "Manhattan", result.address_components_of_type(:sublocality).first['long_name'] end def test_query_url Geocoder.configure(google_premier: {api_key: ["deadbeef", "gme-test", "test-dev"]}) query = Geocoder::Query.new("Madison Square Garden, New York, NY") assert_equal "https://maps.googleapis.com/maps/api/geocode/json?address=Madison+Square+Garden%2C+New+York%2C+NY&channel=test-dev&client=gme-test&language=en&sensor=false&signature=doJvJqX7YJzgV9rJ0DnVkTGZqTg=", query.url end def test_cache_key Geocoder.configure(google_premier: {api_key: ["deadbeef", "gme-test", "test-dev"]}) lookup = Geocoder::Lookup.get(:google_premier) query = Geocoder::Query.new("Madison Square Garden, New York, NY") cache_key = lookup.send(:cache_key, query) assert_equal "https://maps.googleapis.com/maps/api/geocode/json?address=Madison+Square+Garden%2C+New+York%2C+NY&language=en&sensor=false", cache_key end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/google_places_search_test.rb
test/unit/lookups/google_places_search_test.rb
# encoding: utf-8 require 'test_helper' class GooglePlacesSearchTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :google_places_search) set_api_key!(:google_places_search) end def test_google_places_search_result_contains_place_id assert_equal "ChIJhRwB-yFawokR5Phil-QQ3zM", madison_square_garden.place_id end def test_google_places_search_result_contains_latitude assert_equal madison_square_garden.latitude, 40.75050450000001 end def test_google_places_search_result_contains_longitude assert_equal madison_square_garden.longitude, -73.9934387 end def test_google_places_search_result_contains_rating assert_equal 4.5, madison_square_garden.rating end def test_google_places_search_result_contains_types assert_equal madison_square_garden.types, %w(stadium point_of_interest establishment) end def test_google_places_search_query_url_contains_language url = lookup.query_url(Geocoder::Query.new("some-address", language: "de")) assert_match(/language=de/, url) end def test_google_places_search_query_url_contains_input url = lookup.query_url(Geocoder::Query.new("some-address")) assert_match(/input=some-address/, url) end def test_google_places_search_query_url_contains_input_typer url = lookup.query_url(Geocoder::Query.new("some-address")) assert_match(/inputtype=textquery/, url) end def test_google_places_search_query_url_always_uses_https url = lookup.query_url(Geocoder::Query.new("some-address")) assert_match(%r{^https://}, url) end def test_google_places_search_query_url_contains_every_field_available_by_default url = lookup.query_url(Geocoder::Query.new("some-address")) fields = %w[business_status formatted_address geometry icon name photos place_id plus_code types opening_hours price_level rating user_ratings_total] assert_match(/fields=#{fields.join('%2C')}/, url) end def test_google_places_search_query_url_contains_specific_fields_when_given fields = %w[formatted_address place_id] url = lookup.query_url(Geocoder::Query.new("some-address", fields: fields)) assert_match(/fields=#{fields.join('%2C')}/, url) end def test_google_places_search_query_url_contains_specific_fields_when_configured fields = %w[business_status geometry photos] Geocoder.configure(google_places_search: {fields: fields}) url = lookup.query_url(Geocoder::Query.new("some-address")) assert_match(/fields=#{fields.join('%2C')}/, url) Geocoder.configure(google_places_search: {}) end def test_google_places_search_query_url_omits_fields_when_nil_given url = lookup.query_url(Geocoder::Query.new("some-address", fields: nil)) assert_no_match(/fields=/, url) end def test_google_places_search_query_url_omits_fields_when_nil_configured Geocoder.configure(google_places_search: {fields: nil}) url = lookup.query_url(Geocoder::Query.new("some-address")) assert_no_match(/fields=/, url) Geocoder.configure(google_places_search: {}) end def test_google_places_search_query_url_omits_locationbias_by_default url = lookup.query_url(Geocoder::Query.new("some-address")) assert_no_match(/locationbias=/, url) end def test_google_places_search_query_url_contains_locationbias_when_configured Geocoder.configure(google_places_search: {locationbias: "point:-36.8509,174.7645"}) url = lookup.query_url(Geocoder::Query.new("some-address")) assert_match(/locationbias=point%3A-36.8509%2C174.7645/, url) Geocoder.configure(google_places_search: {}) end def test_google_places_search_query_url_contains_locationbias_when_given url = lookup.query_url(Geocoder::Query.new("some-address", locationbias: "point:-36.8509,174.7645")) assert_match(/locationbias=point%3A-36.8509%2C174.7645/, url) end def test_google_places_search_query_url_uses_given_locationbias_over_configured Geocoder.configure(google_places_search: {locationbias: "point:37.4275,-122.1697"}) url = lookup.query_url(Geocoder::Query.new("some-address", locationbias: "point:-36.8509,174.7645")) assert_match(/locationbias=point%3A-36.8509%2C174.7645/, url) Geocoder.configure(google_places_search: {}) end def test_google_places_search_query_url_omits_locationbias_when_nil_given Geocoder.configure(google_places_search: {locationbias: "point:37.4275,-122.1697"}) url = lookup.query_url(Geocoder::Query.new("some-address", locationbias: nil)) assert_no_match(/locationbias=/, url) Geocoder.configure(google_places_search: {}) end def test_google_places_search_query_url_uses_find_place_service url = lookup.query_url(Geocoder::Query.new("some-address")) assert_match(%r{//maps.googleapis.com/maps/api/place/findplacefromtext/}, url) end private def lookup Geocoder::Lookup::GooglePlacesSearch.new end def madison_square_garden Geocoder.search("Madison Square Garden").first end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ip2location_lite_test.rb
test/unit/lookups/ip2location_lite_test.rb
# encoding: utf-8 require 'test_helper' class Ip2locationLiteTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :ip2location_lite, ip2location_lite: { file: File.join('folder', 'test_file') }) end def test_loopback result = Geocoder.search('127.0.0.1').first assert_equal '', result.country_short end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/geocoder_ca_test.rb
test/unit/lookups/geocoder_ca_test.rb
# encoding: utf-8 require 'test_helper' class GeocoderCaTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :geocoder_ca) set_api_key!(:geocoder_ca) end def test_result_components result = Geocoder.search([45.423733, -75.676333]).first assert_equal "CA", result.country_code assert_equal "289 Somerset ST E, Ottawa, ON K1N6W1, Canada", result.address end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/geoip2_test.rb
test/unit/lookups/geoip2_test.rb
# encoding: utf-8 require 'test_helper' class Geoip2Test < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :geoip2, file: 'test_file') end def test_result_attributes result = Geocoder.search('8.8.8.8').first assert_equal 'Mountain View, CA 94043, United States', result.address assert_equal 'Mountain View', result.city assert_equal 'CA', result.state_code assert_equal 'California', result.state assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal '94043', result.postal_code assert_equal 37.41919999999999, result.latitude assert_equal(-122.0574, result.longitude) assert_equal [37.41919999999999, -122.0574], result.coordinates end def test_loopback results = Geocoder.search('127.0.0.1') assert_equal [], results end def test_localization result = Geocoder.search('8.8.8.8').first Geocoder::Configuration.language = :ru assert_equal 'Маунтин-Вью', result.city end def test_dynamic_localization result = Geocoder.search('8.8.8.8').first result.language = :ru assert_equal 'Маунтин-Вью', result.city end def test_dynamic_localization_fallback result = Geocoder.search('8.8.8.8').first result.language = :unsupported_language assert_equal 'Mountain View', result.city assert_equal 'California', result.state assert_equal 'United States', result.country end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/uk_ordnance_survey_names.rb
test/unit/lookups/uk_ordnance_survey_names.rb
# encoding: utf-8 require 'test_helper' class UkOrdnanceSurveyNamesTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :uk_ordnance_survey_names) set_api_key!(:uk_ordnance_survey_names) end def test_result_on_placename_search result = Geocoder.search('London').first assert_in_delta 51.51437, result.coordinates[0] assert_in_delta -0.09227, result.coordinates[1] end def test_result_on_postcode_search result = Geocoder.search('SW1A1AA').first assert_in_delta 51.50100, result.coordinates[0] assert_in_delta -0.14157, result.coordinates[1] end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/telize_test.rb
test/unit/lookups/telize_test.rb
# encoding: utf-8 require 'test_helper' class TelizeTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :telize, telize: {host: nil}) set_api_key!(:telize) end def test_query_url lookup = Geocoder::Lookup::Telize.new query = Geocoder::Query.new("74.200.247.59") assert_match %r{^https://telize-v1\.p\.rapidapi\.com/location/74\.200\.247\.59}, lookup.query_url(query) end def test_includes_api_key_when_set Geocoder.configure(api_key: "api_key") lookup = Geocoder::Lookup::Telize.new query = Geocoder::Query.new("74.200.247.59") assert_match %r{/location/74\.200\.247\.59\?rapidapi-key=api_key}, lookup.query_url(query) end def test_uses_custom_host_when_set Geocoder.configure(telize: {host: "example.com"}) lookup = Geocoder::Lookup::Telize.new query = Geocoder::Query.new("74.200.247.59") assert_match %r{^https://example\.com/location/74\.200\.247\.59$}, lookup.query_url(query) end def test_allows_https_when_custom_host Geocoder.configure(use_https: true, telize: {host: "example.com"}) lookup = Geocoder::Lookup::Telize.new query = Geocoder::Query.new("74.200.247.59") assert_match %r{^https://example\.com}, lookup.query_url(query) end def test_requires_https_when_not_custom_host Geocoder.configure(use_https: false) lookup = Geocoder::Lookup::Telize.new query = Geocoder::Query.new("74.200.247.59") assert_match %r{^https://telize-v1\.p\.rapidapi\.com}, lookup.query_url(query) end def test_result_on_ip_address_search result = Geocoder.search("74.200.247.59").first assert result.is_a?(Geocoder::Result::Telize) end def test_result_on_loopback_ip_address_search result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal '', result.country_code assert_equal '', result.country end def test_result_on_private_ip_address_search result = Geocoder.search("172.19.0.1").first assert_equal "172.19.0.1", result.ip assert_equal '', result.country_code assert_equal '', result.country end def test_result_components result = Geocoder.search("74.200.247.59").first assert_equal "Jersey City, NJ 07302, United States", result.address assert_equal "US", result.country_code assert_equal [40.7209, -74.0468], result.coordinates end def test_no_results results = Geocoder.search("8.8.8.8") assert_equal 0, results.length end def test_invalid_address results = Geocoder.search("555.555.555.555", ip_address: true) assert_equal 0, results.length end def test_cache_key_strips_off_query_string Geocoder.configure(telize: {api_key: "xxxxx"}) lookup = Geocoder::Lookup.get(:telize) query = Geocoder::Query.new("8.8.8.8") qurl = lookup.send(:query_url, query) key = lookup.send(:cache_key, query) assert qurl.include?("rapidapi-key") assert !key.include?("rapidapi-key") end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/maxmind_geoip2_test.rb
test/unit/lookups/maxmind_geoip2_test.rb
# encoding: utf-8 require 'test_helper' class MaxmindGeoip2Test < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :maxmind_geoip2) end def test_result_attributes result = Geocoder.search('1.2.3.4').first assert_equal 'Los Angeles, CA 90001, United States', result.address assert_equal 'Los Angeles', result.city assert_equal 'CA', result.state_code assert_equal 'California', result.state assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal '90001', result.postal_code assert_equal(37.6293, result.latitude) assert_equal(-122.1163, result.longitude) assert_equal [37.6293, -122.1163], result.coordinates end def test_loopback results = Geocoder.search('127.0.0.1') assert_equal [], results end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_dynamic_localization result = Geocoder.search('1.2.3.4').first result.language = :ru assert_equal 'Лос-Анджелес', result.city assert_equal 'Калифорния', result.state assert_equal 'США', result.country end def test_dynamic_localization_fallback result = Geocoder.search('1.2.3.4').first result.language = :unsupported_language assert_equal 'Los Angeles', result.city assert_equal 'California', result.state assert_equal 'United States', result.country end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/pickpoint_test.rb
test/unit/lookups/pickpoint_test.rb
require 'test_helper' class PickpointTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :pickpoint) set_api_key!(:pickpoint) end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "10001", result.postal_code assert_equal "Madison Square Garden, West 31st Street, Long Island City, New York City, New York, 10001, United States of America", result.address end def test_result_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.749828338623, -73.9943389892578, 40.7511596679688, -73.9926528930664], result.viewport end def test_url_contains_api_key Geocoder.configure(pickpoint: {api_key: "pickpoint-api-key"}) query = Geocoder::Query.new("Leadville, CO") assert_match(/key=pickpoint-api-key/, query.url) end def test_raises_exception_with_invalid_api_key Geocoder.configure(always_raise: [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid api key") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/pelias_test.rb
test/unit/lookups/pelias_test.rb
# encoding: utf-8 require 'test_helper' class PeliasTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :pelias, api_key: 'abc123', pelias: {}) # Empty pelias hash only for test (pollution control) end def test_configure_default_endpoint query = Geocoder::Query.new('Madison Square Garden, New York, NY') assert_true query.url.start_with?('https://localhost/v1/search'), query.url end def test_configure_custom_endpoint Geocoder.configure(lookup: :pelias, api_key: 'abc123', pelias: {endpoint: 'self.hosted.pelias/proxy'}) query = Geocoder::Query.new('Madison Square Garden, New York, NY') assert_true query.url.start_with?('https://self.hosted.pelias/proxy/v1/search'), query.url end def test_query_for_reverse_geocode lookup = Geocoder::Lookup::Pelias.new url = lookup.query_url(Geocoder::Query.new([45.423733, -75.676333])) assert_match(/point.lat=45.423733&point.lon=-75.676333/, url) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/maxmind_test.rb
test/unit/lookups/maxmind_test.rb
# encoding: utf-8 require 'test_helper' class MaxmindTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :maxmind) end def test_maxmind_result_on_ip_address_search Geocoder.configure(maxmind: {service: :city_isp_org}) result = Geocoder.search("74.200.247.59").first assert result.is_a?(Geocoder::Result::Maxmind) end def test_maxmind_result_knows_country_service_name Geocoder.configure(maxmind: {service: :country}) assert_equal :country, Geocoder.search("24.24.24.21").first.service_name end def test_maxmind_result_knows_city_service_name Geocoder.configure(maxmind: {service: :city}) assert_equal :city, Geocoder.search("24.24.24.22").first.service_name end def test_maxmind_result_knows_city_isp_org_service_name Geocoder.configure(maxmind: {service: :city_isp_org}) assert_equal :city_isp_org, Geocoder.search("24.24.24.23").first.service_name end def test_maxmind_result_knows_omni_service_name Geocoder.configure(maxmind: {service: :omni}) assert_equal :omni, Geocoder.search("24.24.24.24").first.service_name end def test_maxmind_special_result_components Geocoder.configure(maxmind: {service: :omni}) result = Geocoder.search("24.24.24.24").first assert_equal "Road Runner", result.isp_name assert_equal "Cable/DSL", result.netspeed assert_equal "rr.com", result.domain end def test_maxmind_raises_exception_when_service_not_configured Geocoder.configure(maxmind: {service: nil}) assert_raises Geocoder::ConfigurationError do Geocoder::Query.new("24.24.24.24").url end end def test_maxmind_works_when_loopback_address_on_omni Geocoder.configure(maxmind: {service: :omni}) result = Geocoder.search("127.0.0.1").first assert_equal "", result.country_code end def test_maxmind_works_when_loopback_address_on_country Geocoder.configure(maxmind: {service: :country}) result = Geocoder.search("127.0.0.1").first assert_equal "", result.country_code end def test_maxmind_works_when_private_address_on_omni Geocoder.configure(maxmind: {service: :omni}) result = Geocoder.search("172.19.0.1").first assert_equal "", result.country_code end def test_maxmind_works_when_private_address_on_country Geocoder.configure(maxmind: {service: :country}) result = Geocoder.search("172.19.0.1").first assert_equal "", result.country_code end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/google_places_details_test.rb
test/unit/lookups/google_places_details_test.rb
# encoding: utf-8 require 'test_helper' class GooglePlacesDetailsTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :google_places_details) set_api_key!(:google_places_details) end def test_google_places_details_result_components assert_equal "Manhattan", madison_square_garden.address_components_of_type(:sublocality).first["long_name"] end def test_google_places_details_result_components_contains_route assert_equal "Pennsylvania Plaza", madison_square_garden.address_components_of_type(:route).first["long_name"] end def test_google_places_details_result_components_contains_street_number assert_equal "4", madison_square_garden.address_components_of_type(:street_number).first["long_name"] end def test_google_places_details_street_address_returns_formatted_street_address assert_equal "4 Pennsylvania Plaza", madison_square_garden.street_address end def test_google_places_details_result_contains_place_id assert_equal "ChIJhRwB-yFawokR5Phil-QQ3zM", madison_square_garden.place_id end def test_google_places_details_result_contains_latitude assert_equal madison_square_garden.latitude, 40.750504 end def test_google_places_details_result_contains_longitude assert_equal madison_square_garden.longitude, -73.993439 end def test_google_places_details_result_contains_rating assert_equal 4.4, madison_square_garden.rating end def test_google_places_details_result_contains_rating_count assert_equal 382, madison_square_garden.rating_count end def test_google_places_details_result_contains_reviews reviews = madison_square_garden.reviews assert_equal 2, reviews.size assert_equal "John Smith", reviews.first["author_name"] assert_equal 5, reviews.first["rating"] assert_equal "It's nice.", reviews.first["text"] assert_equal "en", reviews.first["language"] end def test_google_places_details_result_contains_types assert_equal madison_square_garden.types, %w(stadium establishment) end def test_google_places_details_result_contains_website assert_equal madison_square_garden.website, "http://www.thegarden.com/" end def test_google_places_details_result_contains_phone_number assert_equal madison_square_garden.phone_number, "+1 212-465-6741" end def test_google_places_details_query_url_contains_placeid url = lookup.query_url(Geocoder::Query.new("some-place-id")) assert_match(/placeid=some-place-id/, url) end def test_google_places_details_query_url_contains_language url = lookup.query_url(Geocoder::Query.new("some-place-id", language: "de")) assert_match(/language=de/, url) end def test_google_places_details_query_url_always_uses_https url = lookup.query_url(Geocoder::Query.new("some-place-id")) assert_match(%r(^https://), url) end def test_google_places_details_query_url_omits_fields_by_default url = lookup.query_url(Geocoder::Query.new("some-place-id")) assert_no_match(/fields=/, url) end def test_google_places_details_query_url_contains_specific_fields_when_given fields = %w[formatted_address place_id] url = lookup.query_url(Geocoder::Query.new("some-place-id", fields: fields)) assert_match(/fields=#{fields.join('%2C')}/, url) end def test_google_places_details_query_url_contains_specific_fields_when_configured fields = %w[business_status geometry photos] Geocoder.configure(google_places_details: {fields: fields}) url = lookup.query_url(Geocoder::Query.new("some-place-id")) assert_match(/fields=#{fields.join('%2C')}/, url) Geocoder.configure(google_places_details: {}) end def test_google_places_details_query_url_omits_fields_when_nil_given Geocoder.configure(google_places_details: {fields: %w[business_status geometry photos]}) url = lookup.query_url(Geocoder::Query.new("some-place-id", fields: nil)) assert_no_match(/fields=/, url) Geocoder.configure(google_places_details: {}) end def test_google_places_details_query_url_omits_fields_when_nil_configured Geocoder.configure(google_places_details: {fields: nil}) url = lookup.query_url(Geocoder::Query.new("some-place-id")) assert_no_match(/fields=/, url) Geocoder.configure(google_places_details: {}) end def test_google_places_details_result_with_no_reviews_shows_empty_reviews assert_equal no_reviews_result.reviews, [] end def test_google_places_details_result_with_no_types_shows_empty_types assert_equal no_types_result.types, [] end def test_google_places_details_result_with_invalid_place_id_empty silence_warnings do assert_equal Geocoder.search("invalid request"), [] end end def test_raises_exception_on_google_places_details_invalid_request Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search("invalid request") end end private def lookup Geocoder::Lookup::GooglePlacesDetails.new end def madison_square_garden Geocoder.search("ChIJhRwB-yFawokR5Phil-QQ3zM").first end def no_reviews_result Geocoder.search("no reviews").first end def no_types_result Geocoder.search("no types").first end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/mapbox_test.rb
test/unit/lookups/mapbox_test.rb
# encoding: utf-8 require 'test_helper' class MapboxTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :mapbox) set_api_key!(:mapbox) end def test_url_contains_api_key Geocoder.configure(mapbox: {api_key: "abc123"}) query = Geocoder::Query.new("Leadville, CO") assert_equal "https://api.mapbox.com/geocoding/v5/mapbox.places/Leadville%2C%20CO.json?access_token=abc123", query.url end def test_url_contains_params Geocoder.configure(mapbox: {api_key: "abc123"}) query = Geocoder::Query.new("Leadville, CO", {params: {country: 'CN'}}) assert_equal "https://api.mapbox.com/geocoding/v5/mapbox.places/Leadville%2C%20CO.json?access_token=abc123&country=CN", query.url end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.750755, -73.993710125], result.coordinates assert_equal "Madison Square Garden, 4 Penn Plz, New York, New York 10119, United States", result.place_name assert_equal "4 Penn Plz", result.street assert_equal "New York", result.city assert_equal "New York", result.state assert_equal "10119", result.postal_code assert_equal "NY", result.state_code assert_equal "United States", result.country assert_equal "US", result.country_code assert_equal "Garment District", result.neighborhood assert_equal "Madison Square Garden, 4 Penn Plz, New York, New York 10119, United States", result.address end def test_no_results assert_equal [], Geocoder.search("no results") end def test_raises_exception_with_invalid_api_key Geocoder.configure(always_raise: [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid api key") end end def test_empty_array_on_invalid_api_key assert_equal [], Geocoder.search("invalid api key") end def test_truncates_query_at_semicolon result = Geocoder.search("Madison Square Garden, New York, NY;123 Another St").first assert_equal [40.750755, -73.993710125], result.coordinates end def test_mapbox_result_without_context assert_nothing_raised do result = Geocoder.search("Shanghai, China")[0] assert_equal nil, result.city end end def test_neighborhood_result result = Geocoder.search("Logan Square, Chicago, IL").first assert_equal [41.92597, -87.70235], result.coordinates assert_equal "Logan Square, Chicago, Illinois, United States", result.place_name assert_equal nil, result.street assert_equal "Chicago", result.city assert_equal "Illinois", result.state assert_equal "60647", result.postal_code assert_equal "IL", result.state_code assert_equal "United States", result.country assert_equal "US", result.country_code assert_equal "Logan Square", result.neighborhood assert_equal "Logan Square, Chicago, Illinois, United States", result.address end def test_postcode_result result = Geocoder.search("Chicago, IL 60647").first assert_equal [41.924799, -87.700436], result.coordinates assert_equal "Chicago, Illinois 60647, United States", result.place_name assert_equal nil, result.street assert_equal "Chicago", result.city assert_equal "Illinois", result.state assert_equal "60647", result.postal_code assert_equal "IL", result.state_code assert_equal "United States", result.country assert_equal "US", result.country_code assert_equal nil, result.neighborhood assert_equal "Chicago, Illinois 60647, United States", result.address end def test_place_result result = Geocoder.search("Chicago, IL").first assert_equal [41.881954, -87.63236], result.coordinates assert_equal "Chicago, Illinois, United States", result.place_name assert_equal nil, result.street assert_equal "Chicago", result.city assert_equal "Illinois", result.state assert_equal nil, result.postal_code assert_equal "IL", result.state_code assert_equal "United States", result.country assert_equal "US", result.country_code assert_equal nil, result.neighborhood assert_equal "Chicago, Illinois, United States", result.address end def test_region_result result = Geocoder.search("Illinois").first assert_equal [40.1492928594374, -89.2749461071049], result.coordinates assert_equal "Illinois, United States", result.place_name assert_equal nil, result.street assert_equal nil, result.city assert_equal "Illinois", result.state assert_equal nil, result.postal_code assert_equal "IL", result.state_code assert_equal "United States", result.country assert_equal "US", result.country_code assert_equal nil, result.neighborhood assert_equal "Illinois, United States", result.address end def test_country_result result = Geocoder.search("United States").first assert_equal [39.3812661305678, -97.9222112121185], result.coordinates assert_equal "United States", result.place_name assert_equal nil, result.street assert_equal nil, result.city assert_equal nil, result.state assert_equal nil, result.postal_code assert_equal nil, result.state_code assert_equal "United States", result.country assert_equal "US", result.country_code assert_equal nil, result.neighborhood assert_equal "United States", result.address end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipregistry_test.rb
test/unit/lookups/ipregistry_test.rb
# encoding: utf-8 require 'test_helper' class IpregistryTest < GeocoderTestCase def test_lookup_loopback_address Geocoder.configure(:ip_lookup => :ipregistry) result = Geocoder.search("127.0.0.1").first assert_nil result.latitude assert_nil result.longitude assert_equal "127.0.0.1", result.ip end def test_lookup_private_address Geocoder.configure(:ip_lookup => :ipregistry) result = Geocoder.search("172.19.0.1").first assert_nil result.latitude assert_nil result.longitude assert_equal "172.19.0.1", result.ip end def test_known_ip_address Geocoder.configure(:ip_lookup => :ipregistry) result = Geocoder.search("8.8.8.8").first assert_equal "8.8.8.8", result.ip assert_equal "California", result.state assert_equal "USD", result.currency_code assert_equal "NA", result.location_continent_code assert_equal "US", result.location_country_code assert_equal false, result.security_is_tor assert_equal "America/Los_Angeles", result.time_zone_id end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/azure_test.rb
test/unit/lookups/azure_test.rb
require 'test_helper' class AzureTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :azure, azure: { limit: 1 }) set_api_key!(:azure) end def test_azure_results_jakarta_properties result = Geocoder.search('Jakarta').first assert_equal 'Jakarta', result&.city assert_equal 'Indonesia', result&.country assert_equal 'Jakarta, Jakarta', result&.address end def test_azure_results_jakarta_coordinates result = Geocoder.search('Jakarta').first assert_equal(-6.17476, result&.coordinates[0]) assert_equal(106.82707, result&.coordinates[1]) end def test_azure_results_jakarta_viewport result = Geocoder.search('Jakarta').first assert_equal( { 'topLeftPoint' => { 'lat' => -5.95462, 'lon' => 106.68588 }, 'btmRightPoint'=> { 'lat' => -6.37083, 'lon' => 106.9729 } }, result&.viewport ) end def test_azure_reverse_results_properties result = Geocoder.search([-6.198967624433219, 106.82358133258361]).first assert_equal 'Jakarta', result&.city assert_equal 'Indonesia', result&.country assert_equal 'Jalan Mohammad Husni Thamrin 10, Kecamatan Jakarta, DKI Jakarta 10230', result&.address end def test_azure_no_result result = Geocoder.search('no results') assert_equal 0, result&.length end def test_azure_results_no_street_number result = Geocoder.search('Jakarta').first assert_equal nil, result&.street_number end def test_query_url query = Geocoder::Query.new('Jakarta') assert_equal 'https://atlas.microsoft.com/search/address/json?api-version=1.0&language=en&limit=1&query=Jakarta&subscription-key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', query.url end def test_reverse_query_url query = Geocoder::Query.new([-6.198967624433219, 106.82358133258361]) assert_equal "https://atlas.microsoft.com/search/address/reverse/json?api-version=1.0&language=en&limit=1&query=-6.198967624433219%2C106.82358133258361&subscription-key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", query.url end def test_azure_query_url_contains_api_key lookup = Geocoder::Lookup::Azure.new url = lookup.query_url( Geocoder::Query.new( 'Test Query' ) ) assert_match(/subscription-key=a+/, url) end def test_azure_query_url_contains_language lookup = Geocoder::Lookup::Azure.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', language: 'en' ) ) assert_match(/language=en/, url) end def test_azure_query_url_contains_text lookup = Geocoder::Lookup::Azure.new url = lookup.query_url( Geocoder::Query.new( 'PT Kulkul Teknologi Internasional' ) ) assert_match(/PT\+Kulkul\+Teknologi\+Internasional/i, url) end def test_azure_reverse_query_url_contains_lat_lon lookup = Geocoder::Lookup::Azure.new url = lookup.query_url( Geocoder::Query.new( [-6.198967624433219, 106.82358133258361] ) ) assert_match(/query=-6\.198967624433219%2C106\.82358133258361/, url) end def test_azure_invalid_key result = Geocoder.search('invalid key').first assert_equal 'InvalidKey', result&.data&.last['code'] assert_equal 'The provided key was incorrect or the account resource does not exist.', result&.data&.last['message'] end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/pc_miler_test.rb
test/unit/lookups/pc_miler_test.rb
# encoding: utf-8 require 'test_helper' class TrimbleMapsTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :pc_miler) end def test_query_for_geocode query = Geocoder::Query.new('wall drug') lookup = Geocoder::Lookup.get(:pc_miler) res = lookup.query_url(query) assert_equal 'https://singlesearch.alk.com/NA/api/search?include=Meta&query=wall+drug', res end def test_query_for_geocode_with_commas query = Geocoder::Query.new('Fair Lawn, NJ, US') lookup = Geocoder::Lookup.get(:pc_miler) res = lookup.query_url(query) assert_equal 'https://singlesearch.alk.com/NA/api/search?include=Meta&query=Fair+Lawn%2C+NJ%2C+US', res end def test_query_for_reverse_geocode query = Geocoder::Query.new([43.99255, -102.24127]) lookup = Geocoder::Lookup.get(:pc_miler) res = lookup.query_url(query) assert_equal 'https://singlesearch.alk.com/NA/api/search?include=Meta&query=43.99255%2C-102.24127', res end def test_not_authorized Geocoder.configure(always_raise: [Geocoder::RequestDenied]) lookup = Geocoder::Lookup.get(:pc_miler) assert_raises Geocoder::RequestDenied do response = MockHttpResponse.new(code: 403) lookup.send(:check_response_for_errors!, response) end end def test_query_region_defaults_to_north_america query = Geocoder::Query.new('Sydney') lookup = Geocoder::Lookup.get(:pc_miler) res = lookup.query_url(query) assert_equal 'https://singlesearch.alk.com/NA/api/search?include=Meta&query=Sydney', res end def test_query_region_can_be_given_in_global_config Geocoder.configure(lookup: :pc_miler, pc_miler: { region: 'EU' }) query = Geocoder::Query.new('Sydney') lookup = Geocoder::Lookup.get(:pc_miler) res = lookup.query_url(query) assert_equal 'https://singlesearch.alk.com/EU/api/search?include=Meta&query=Sydney', res end # option given in query takes precedence over global option def test_query_region_can_be_given_in_query Geocoder.configure(lookup: :pc_miler, pc_miler: { region: 'EU' }) query = Geocoder::Query.new('Sydney', region: 'OC') lookup = Geocoder::Lookup.get(:pc_miler) res = lookup.query_url(query) assert_equal 'https://singlesearch.alk.com/OC/api/search?include=Meta&query=Sydney', res end def test_query_raises_if_region_is_invalid query = Geocoder::Query.new('Sydney', region: 'QQ') lookup = Geocoder::Lookup.get(:pc_miler) error = assert_raises do lookup.query_url(query) end assert_match(/region_code 'QQ' is invalid/, error.message) end def test_results_with_street_address results = Geocoder.search('wall drug') assert_equal 2, results.size result = results[0] assert_equal '510 Main St', result.street assert_equal 'Wall', result.city assert_equal 'South Dakota', result.state assert_equal 'SD', result.state_code assert_equal '57790-9501', result.postal_code assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal '510 Main St, Wall, South Dakota, 57790-9501, United States', result.address assert_equal 44.0632, result.latitude assert_equal(-102.2151, result.longitude) assert_equal([44.0632, -102.2151], result.coordinates) end def test_results_without_street_address results = Geocoder.search('Duluth MN') assert_equal 1, results.size result = results[0] assert_equal '', result.street assert_equal 'Duluth', result.city assert_equal 'Minnesota', result.state assert_equal 'MN', result.state_code assert_equal '55806', result.postal_code assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal 'Duluth, Minnesota, 55806, United States', result.address assert_equal 46.776443, result.latitude assert_equal(-92.110529, result.longitude) assert_equal([46.776443, -92.110529], result.coordinates) end def test_results_reverse_geocoding results = Geocoder.search([42.14228, -102.85796]) assert_equal 1, results.size result = results[0] assert_equal '2093 NE-87', result.street assert_equal 'Alliance', result.city assert_equal 'Nebraska', result.state assert_equal 'NE', result.state_code assert_equal '69301', result.postal_code assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal '2093 NE-87, Alliance, Nebraska, 69301, United States', result.address assert_equal 42.14228, result.latitude assert_equal(-102.85796, result.longitude) assert_equal([42.14228, -102.85796], result.coordinates) end def test_results_metadata results = Geocoder.search("Times Square") assert_equal 10, results.size results.map do |result| assert_equal 3, result.data["QueryConfidence"] end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ban_data_gouv_fr_test.rb
test/unit/lookups/ban_data_gouv_fr_test.rb
# encoding: utf-8 require 'test_helper' class BanDataGouvFrTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :ban_data_gouv_fr, use_https: true) end def test_query_for_geocode query = Geocoder::Query.new('13 rue yves toudic, 75010 Paris') lookup = Geocoder::Lookup.get(:ban_data_gouv_fr) res = lookup.query_url(query) assert_equal 'https://data.geopf.fr/geocodage/search/?q=13+rue+yves+toudic%2C+75010+Paris', res end def test_query_for_geocode_with_geographic_priority query = Geocoder::Query.new('13 rue yves toudic, 75010 Paris', lat: 48.789, lon: 2.789) lookup = Geocoder::Lookup.get(:ban_data_gouv_fr) res = lookup.query_url(query) assert_equal 'https://data.geopf.fr/geocodage/search/?lat=48.789&lon=2.789&q=13+rue+yves+toudic%2C+75010+Paris', res end def test_query_for_reverse_geocode query = Geocoder::Query.new([48.770639, 2.364375]) lookup = Geocoder::Lookup.get(:ban_data_gouv_fr) res = lookup.query_url(query) assert_equal 'https://data.geopf.fr/geocodage/reverse/?lat=48.770639&lon=2.364375', res end def test_results_component result = Geocoder.search('13 rue yves toudic, 75010 Paris').first assert_equal 'ADRNIVX_0000000270748760', result.location_id assert_equal 'housenumber', result.result_type assert_equal 'Paris', result.city_name assert_equal '13 Rue Yves Toudic 75010 Paris, France', result.international_address assert_equal '13 Rue Yves Toudic 75010 Paris, France', result.address assert_equal '13 Rue Yves Toudic 75010 Paris', result.national_address assert_equal '13 Rue Yves Toudic', result.street_address assert_equal '13', result.street_number assert_equal 'Rue Yves Toudic', result.street assert_equal 'Rue Yves Toudic', result.street_name assert_equal 'Paris', result.city assert_equal 'Paris', result.city_name assert_equal '75110', result.city_code assert_equal '75010', result.postal_code assert_equal '75', result.department_code assert_equal 'Paris', result.department_name assert_equal 'Île-de-France', result.region_name assert_equal '11', result.region_code assert_equal 'France', result.country assert_equal 'FR', result.country_code assert_equal(48.870131, result.coordinates[0]) assert_equal(2.363473, result.coordinates[1]) end def test_paris_special_business_logic result = Geocoder.search('paris').first assert_equal 'municipality', result.result_type assert_equal '75000', result.postal_code assert_equal 'France', result.country assert_equal 'FR', result.country_code assert_equal(2244000, result.population) assert_equal 'Paris', result.city assert_equal 'Paris', result.city_name assert_equal '75056', result.city_code assert_equal '75000', result.postal_code assert_equal '75', result.department_code assert_equal 'Paris', result.department_name assert_equal 'Île-de-France', result.region_name assert_equal '11', result.region_code assert_equal(48.8589, result.coordinates[0]) assert_equal(2.3469, result.coordinates[1]) end def test_city_result_methods result = Geocoder.search('montpellier', type: 'municipality').first assert_equal 'municipality', result.result_type assert_equal '34080', result.postal_code assert_equal '34172', result.city_code assert_equal 'France', result.country assert_equal 'FR', result.country_code assert_equal(5, result.administrative_weight) assert_equal(255100, result.population) assert_equal '34', result.department_code assert_equal 'Hérault', result.department_name assert_equal 'Occitanie', result.region_name assert_equal '76', result.region_code assert_equal(43.611024, result.coordinates[0]) assert_equal(3.875521, result.coordinates[1]) end def test_results_component_when_reverse_geocoding result = Geocoder.search([48.770431, 2.364463]).first assert_equal '94021_1133_49638b', result.location_id assert_equal 'housenumber', result.result_type assert_equal '4 Rue du Lieutenant Alain le Coz 94550 Chevilly-Larue, France', result.international_address assert_equal '4 Rue du Lieutenant Alain le Coz 94550 Chevilly-Larue, France', result.address assert_equal '4 Rue du Lieutenant Alain le Coz 94550 Chevilly-Larue', result.national_address assert_equal '4 Rue du Lieutenant Alain le Coz', result.street_address assert_equal '4', result.street_number assert_equal 'Rue du Lieutenant Alain le Coz', result.street assert_equal 'Rue du Lieutenant Alain le Coz', result.street_name assert_equal 'Chevilly-Larue', result.city assert_equal 'Chevilly-Larue', result.city_name assert_equal '94021', result.city_code assert_equal '94550', result.postal_code assert_equal '94', result.department_code assert_equal 'Val-de-Marne', result.department_name assert_equal 'Île-de-France', result.region_name assert_equal '11', result.region_code assert_equal 'France', result.country assert_equal 'FR', result.country_code assert_equal(48.770639, result.coordinates[0]) assert_equal(2.364375, result.coordinates[1]) end def test_no_reverse_results result = Geocoder.search('no reverse results') assert_equal 0, result.length end def test_actual_make_api_request_with_https Geocoder.configure(use_https: true, lookup: :ban_data_gouv_fr) require 'webmock/test_unit' WebMock.enable! stub_all = WebMock.stub_request(:any, /.*/).to_return(status: 200) g = Geocoder::Lookup::BanDataGouvFr.new g.send(:actual_make_api_request, Geocoder::Query.new('test location')) assert_requested(stub_all) WebMock.reset! WebMock.disable! end private def assert_country_code(result) [:state_code, :country_code, :province_code].each do |method| assert_equal 'FR', result.send(method) end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/geocodio_test.rb
test/unit/lookups/geocodio_test.rb
# encoding: utf-8 require 'test_helper' class GeocodioTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :geocodio) set_api_key!(:geocodio) end def test_result_components result = Geocoder.search("1101 Pennsylvania Ave NW, Washington DC").first assert_equal 1.0, result.accuracy assert_equal "1101", result.number assert_equal "1101 Pennsylvania Ave NW", result.street_address assert_equal "Ave", result.suffix assert_equal "DC", result.state assert_equal "20004", result.zip assert_equal "NW", result.postdirectional assert_equal "Washington", result.city assert_equal "US", result.country_code assert_equal "United States", result.country assert_equal "1101 Pennsylvania Ave NW, Washington, DC 20004", result.formatted_address assert_equal({ "lat" => 38.895343, "lng" => -77.027385 }, result.location) end def test_reverse_canada_result result = Geocoder.search([43.652961, -79.382624]).first assert_equal 1.0, result.accuracy assert_equal "483", result.number assert_equal "Bay", result.street assert_equal "St", result.suffix assert_equal "ON", result.state assert_equal "Toronto", result.city assert_equal "CA", result.country_code assert_equal "Canada", result.country end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_geocodio_reverse_url query = Geocoder::Query.new([45.423733, -75.676333]) assert_match(/reverse/, query.url) end def test_raises_invalid_request_exception Geocoder.configure(:always_raise => [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search("invalid") end end def test_raises_api_key_exception Geocoder.configure(:always_raise => [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("bad api key") end end def test_raises_over_limit_exception Geocoder.configure(:always_raise => [Geocoder::OverQueryLimitError]) assert_raises Geocoder::OverQueryLimitError do Geocoder.search("over query limit") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipgeolocation_test.rb
test/unit/lookups/ipgeolocation_test.rb
# encoding: utf-8 require 'test_helper' class IpgeolocationTest < GeocoderTestCase def setup super Geocoder.configure( :api_key => 'ea91e4a4159247fdb0926feae70c2911', :ip_lookup => :ipgeolocation, :always_raise => :all ) end def test_result_on_ip_address_search result = Geocoder.search("103.217.177.217").first assert result.is_a?(Geocoder::Result::Ipgeolocation) end def test_result_components result = Geocoder.search("103.217.177.217").first assert_equal "Pakistan", result.country_name end def test_all_top_level_api_fields result = Geocoder.search("103.217.177.217").first assert_equal "103.217.177.217", result.ip assert_equal "AS", result.continent_code assert_equal "Asia", result.continent_name assert_equal "PK", result.country_code2 assert_equal "Pakistan", result.country_name assert_equal "Islamabad", result.city assert_equal "44000", result.zipcode assert_equal 33.7334, result.latitude assert_equal 73.0785, result.longitude end def test_nested_api_fields result = Geocoder.search("103.217.177.217").first assert result.time_zone.is_a?(Hash) assert_equal "Asia/Karachi", result.time_zone['name'] assert result.currency.is_a?(Hash) assert_equal "PKR", result.currency['code'] end def test_required_base_fields result = Geocoder.search("103.217.177.217").first assert_equal "Islamabad", result.country_capital assert_equal "Islamabad", result.state_prov assert_equal "Islamabad", result.city assert_equal "44000", result.zipcode assert_equal [33.7334, 73.0785], result.coordinates end def test_localhost_loopback result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal "RD", result.country_code2 assert_equal "Reserved", result.country_name end def test_localhost_loopback_defaults result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal "", result.continent_code assert_equal "", result.continent_name assert_equal "RD", result.country_code2 assert_equal "Reserved", result.country_name assert_equal "", result.city assert_equal "", result.zipcode assert_equal 0, result.latitude assert_equal 0, result.longitude assert_equal({}, result.time_zone) assert_equal({}, result.currency) end def test_localhost_private result = Geocoder.search("172.19.0.1").first assert_equal "172.19.0.1", result.ip assert_equal "RD", result.country_code2 assert_equal "Reserved", result.country_name end def test_api_request_adds_access_key lookup = Geocoder::Lookup.get(:ipgeolocation) assert_match(/apiKey=\w+/, lookup.query_url(Geocoder::Query.new("74.200.247.59"))) end def test_api_request_adds_security_when_specified lookup = Geocoder::Lookup.get(:ipgeolocation) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { security: '1' })) assert_match(/&security=1/, query_url) end def test_api_request_adds_hostname_when_specified lookup = Geocoder::Lookup.get(:ipgeolocation) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { hostname: '1' })) assert_match(/&hostname=1/, query_url) end def test_api_request_adds_language_when_specified lookup = Geocoder::Lookup.get(:ipgeolocation) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { language: 'es' })) assert_match(/&language=es/, query_url) end def test_api_request_adds_fields_when_specified lookup = Geocoder::Lookup.get(:ipgeolocation) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { fields: 'foo,bar' })) assert_match(/&fields=foo%2Cbar/, query_url) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/opencagedata_test.rb
test/unit/lookups/opencagedata_test.rb
# encoding: utf-8 require 'test_helper' class OpencagedataTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :opencagedata) set_api_key!(:opencagedata) end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "West 31st Street", result.street assert_match(/46, West 31st Street, Koreatown, New York County, 10011, New York City, New York, United States of America/, result.address) end def test_opencagedata_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.7498531, -73.9944444, 40.751161, -73.9925922], result.viewport end def test_opencagedata_query_url_contains_bounds lookup = Geocoder::Lookup::Opencagedata.new url = lookup.query_url(Geocoder::Query.new( "Some street", :bounds => [[40.0, -120.0], [39.0, -121.0]] )) assert_match(/bounds=40.0+%2C-120.0+%2C39.0+%2C-121.0+/, url) end def test_opencagedata_query_url_contains_optional_params lookup = Geocoder::Lookup::Opencagedata.new url = lookup.query_url(Geocoder::Query.new( "Some street", :countrycode => 'fr', :min_confidence => 5, :no_dedupe => 1, :no_annotations => 1, :no_record => 1, :limit => 2 )) assert_match(/countrycode=fr/, url) assert_match(/min_confidence=5/, url) assert_match(/no_dedupe=1/, url) assert_match(/no_annotations=1/, url) assert_match(/no_record=1/, url) assert_match(/limit=2/, url) end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_opencagedata_reverse_url query = Geocoder::Query.new([45.423733, -75.676333]) assert_match(/\bq=45.423733%2C-75.676333\b/, query.url) end def test_opencagedata_time_zone result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "America/New_York", result.time_zone end def test_raises_exception_when_invalid_request Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search("invalid request") end end def test_raises_exception_when_invalid_api_key Geocoder.configure(always_raise: [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid api key") end end def test_raises_exception_when_over_query_limit Geocoder.configure(:always_raise => [Geocoder::OverQueryLimitError]) l = Geocoder::Lookup.get(:opencagedata) assert_raises Geocoder::OverQueryLimitError do l.send(:results, Geocoder::Query.new("over limit")) end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/melissa_street_test.rb
test/unit/lookups/melissa_street_test.rb
# encoding: utf-8 require 'test_helper' class MelissaStreetTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :melissa_street) set_api_key!(:melissa_street) end def test_result_components result = Geocoder.search("1 Frank H Ogawa Plz Fl 3").first assert_equal "1", result.number assert_equal "1 Frank H Ogawa Plz Fl 3", result.street_address assert_equal "Plz", result.suffix assert_equal "CA", result.state assert_equal "94612-1932", result.postal_code assert_equal "Oakland", result.city assert_equal "US", result.country_code assert_equal "United States of America", result.country assert_equal([37.805402, -122.272797], result.coordinates) end def test_low_accuracy result = Geocoder.search("low accuracy").first assert_equal "United States of America", result.country end def test_raises_api_key_exception Geocoder.configure(:always_raise => [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid key") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ip2location_test.rb
test/unit/lookups/ip2location_test.rb
# encoding: utf-8 require 'test_helper' class Ip2locationTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :ip2location) set_api_key!(:ip2location) end def test_ip2location_query_url query = Geocoder::Query.new('8.8.8.8') assert_equal 'https://api.ip2location.com/v2/?ip=8.8.8.8&key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', query.url end def test_ip2location_query_url_with_package Geocoder.configure(ip2location: {package: 'WS3'}) query = Geocoder::Query.new('8.8.8.8') assert_equal 'https://api.ip2location.com/v2/?ip=8.8.8.8&key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa&package=WS3', query.url end def test_ip2location_lookup_address result = Geocoder.search("8.8.8.8").first assert_equal "US", result.country_code end def test_ip2location_lookup_loopback_address result = Geocoder.search("127.0.0.1").first assert_equal "INVALID IP ADDRESS", result.country_code end def test_ip2location_lookup_private_address result = Geocoder.search("172.19.0.1").first assert_equal "INVALID IP ADDRESS", result.country_code end def test_ip2location_extra_data Geocoder.configure(:ip2location => {:package => "WS3"}) result = Geocoder.search("8.8.8.8").first assert_equal "United States", result.country_name assert_equal "California", result.region_name assert_equal "Mountain View", result.city_name end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/mapquest_test.rb
test/unit/lookups/mapquest_test.rb
# encoding: utf-8 require 'test_helper' class MapquestTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :mapquest) set_api_key!(:mapquest) end def test_url_contains_api_key Geocoder.configure(mapquest: {api_key: "abc123"}) query = Geocoder::Query.new("Bluffton, SC") assert_equal "https://www.mapquestapi.com/geocoding/v1/address?key=abc123&location=Bluffton%2C+SC", query.url end def test_url_for_open_street_maps Geocoder.configure(mapquest: {api_key: "abc123", open: true}) query = Geocoder::Query.new("Bluffton, SC") assert_equal "https://open.mapquestapi.com/geocoding/v1/address?key=abc123&location=Bluffton%2C+SC", query.url end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "10001", result.postal_code assert_equal "46 West 31st Street, New York, NY, 10001, US", result.address end def test_no_results assert_equal [], Geocoder.search("no results") end def test_raises_exception_when_invalid_request Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search("invalid request") end end def test_raises_exception_when_invalid_api_key Geocoder.configure(always_raise: [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid api key") end end def test_raises_exception_when_error Geocoder.configure(always_raise: [Geocoder::Error]) assert_raises Geocoder::Error do Geocoder.search("error") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ip2location_io_test.rb
test/unit/lookups/ip2location_io_test.rb
# encoding: utf-8 require 'test_helper' class Ip2locationIoTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :ip2location_io) set_api_key!(:ip2location_io) end def test_ip2location_io_query_url query = Geocoder::Query.new('8.8.8.8') assert_equal 'https://api.ip2location.io/?ip=8.8.8.8&key=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', query.url end def test_ip2location_io_lookup_address result = Geocoder.search("8.8.8.8").first assert_equal "US", result.country_code assert_equal "United States of America", result.country_name assert_equal "California", result.region_name assert_equal "Mountain View", result.city_name end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/maxmind_local_test.rb
test/unit/lookups/maxmind_local_test.rb
# encoding: utf-8 require 'test_helper' class MaxmindLocalTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :maxmind_local) end def test_result_attributes result = Geocoder.search('8.8.8.8').first assert_equal 'Mountain View, CA 94043, United States', result.address assert_equal 'Mountain View', result.city assert_equal 'CA', result.state assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal '94043', result.postal_code assert_equal(37.41919999999999, result.latitude) assert_equal(-122.0574, result.longitude) assert_equal [37.41919999999999, -122.0574], result.coordinates end def test_loopback results = Geocoder.search('127.0.0.1') assert_equal [], results end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/location_iq_test.rb
test/unit/lookups/location_iq_test.rb
# encoding: utf-8 require 'unit/lookups/nominatim_test' require 'test_helper' class LocationIq < NominatimTest def setup super Geocoder.configure(lookup: :location_iq) set_api_key!(:location_iq) end def test_url_contains_api_key Geocoder.configure(location_iq: {api_key: "abc123"}) query = Geocoder::Query.new("Leadville, CO") assert_match(/key=abc123/, query.url) end def test_raises_exception_with_invalid_api_key Geocoder.configure(always_raise: [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid api key") end end def test_raises_exception_with_request_denied Geocoder.configure(always_raise: [Geocoder::RequestDenied]) assert_raises Geocoder::RequestDenied do Geocoder.search("request denied") end end def test_raises_exception_with_rate_limited Geocoder.configure(always_raise: [Geocoder::OverQueryLimitError]) assert_raises Geocoder::OverQueryLimitError do Geocoder.search("over limit") end end def test_raises_exception_with_invalid_request Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search("invalid request") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/abstract_api_test.rb
test/unit/lookups/abstract_api_test.rb
# encoding: utf-8 require 'test_helper' class AbstractApiTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :abstract_api) set_api_key!(:abstract_api) end def test_result_attributes result = Geocoder.search('2.19.128.50').first assert_equal 'Seattle, WA 98111, United States', result.address assert_equal 'Seattle', result.city assert_equal 'WA', result.state_code assert_equal 'Washington', result.state assert_equal 'United States', result.country assert_equal 'US', result.country_code assert_equal '98111', result.postal_code assert_equal 47.6032, result.latitude assert_equal(-122.3412, result.longitude) assert_equal [47.6032, -122.3412], result.coordinates end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/latlon_test.rb
test/unit/lookups/latlon_test.rb
# encoding: utf-8 require 'test_helper' class LatlonTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :latlon) set_api_key!(:latlon) end def test_result_components result = Geocoder.search("6000 Universal Blvd, Orlando, FL 32819").first assert_equal "6000", result.number assert_equal "Universal", result.street_name assert_equal "Blvd", result.street_type assert_equal "Universal Blvd", result.street assert_equal "Orlando", result.city assert_equal "FL", result.state assert_equal "32819", result.zip assert_equal "6000 Universal Blvd, Orlando, FL 32819", result.formatted_address assert_equal(28.4750507575094, result.latitude) assert_equal(-81.4630386931719, result.longitude) end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_latlon_reverse_url query = Geocoder::Query.new([45.423733, -75.676333]) assert_match(/reverse_geocode/, query.url) end def test_raises_api_key_exception Geocoder.configure Geocoder.configure(:always_raise => [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search("invalid key") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/geoapify_test.rb
test/unit/lookups/geoapify_test.rb
# frozen_string_literal: true require 'test_helper' class GeoapifyTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :geoapify) set_api_key!(:geoapify) end def test_geoapify_forward_geocoding_result_properties result = Geocoder.search('Madison Square Garden, New York, NY').first geometry = { type: "Point", coordinates: [ -73.99351594545152, 40.750512900000004 ] } bounds = [ -73.9944193, 40.7498726, -73.9925924, 40.7511643 ] rank = { importance: 0.6456870542995358, popularity: 8.615793062435909, confidence: 1, confidence_city_level: 1, match_type: :full_match } datasource = { sourcename: "openstreetmap", attribution: "© OpenStreetMap contributors", license: "Open Database License", url: "https://www.openstreetmap.org/copyright" } assert_equal(40.750512900000004, result.latitude) assert_equal(-73.99351594545152, result.longitude) assert_equal 'Madison Square Garden', result.address_line1 assert_equal '4 Pennsylvania Plaza, New York, NY 10001, United States of America', result.address_line2 assert_equal '4', result.house_number assert_equal 'Pennsylvania Plaza', result.street assert_equal 'Manhattan', result.district assert_nil result.suburb assert_equal 'New York County', result.county assert_equal 'NY', result.state_code assert_equal 'New York', result.state assert_equal 'US', result.country_code assert_equal 'United States', result.country assert_equal '10001', result.postal_code assert_equal geometry, result.geometry assert_equal bounds, result.bounds assert_equal :amenity, result.type assert_nil result.distance # Only for reverse geocoding requests assert_equal rank, result.rank assert_equal datasource, result.datasource end def test_geoapify_reverse_geocoding_result_properties result = Geocoder.search([40.750512900000004, -73.99351594545152]).first geometry = { "type": "Point", "coordinates": [ -73.9935443, 40.7505085 ] } bounds = [ -73.9935943, 40.7504585, -73.9934943, 40.7505585 ] rank = { importance: 0.00000999999999995449, popularity: 8.615793062435909 } datasource = { sourcename: "openstreetmap", attribution: "© OpenStreetMap contributors", license: "Open Database License", url: "https://www.openstreetmap.org/copyright" } assert_equal(40.7505085, result.latitude) assert_equal(-73.9935443, result.longitude) assert_equal '4 Pennsylvania Plaza', result.address_line1 assert_equal 'New York, NY 10001, United States of America', result.address_line2 assert_equal '4', result.house_number assert_equal 'Pennsylvania Plaza', result.street assert_equal 'Manhattan', result.district assert_nil result.suburb assert_equal 'New York County', result.county assert_equal geometry, result.geometry assert_equal bounds, result.bounds assert_equal :building, result.type assert_equal 2.438092698242724, result.distance assert_equal rank, result.rank assert_equal datasource, result.datasource end def test_geoapify_query_url_contains_language lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', language: 'de' ) ) assert_match(/lang=de/, url) end def test_geoapify_query_url_contains_limit lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', limit: 5 ) ) assert_match(/limit=5/, url) end def test_geoapify_query_url_contains_api_key lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( 'Test Query' ) ) assert_match(/apiKey=a+/, url) end def test_geoapify_query_url_contains_text lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( 'Test Query' ) ) assert_match(/text=Test\+Query/, url) end def test_geoapify_query_url_contains_params lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', params: { type: 'amenity', filter: 'countrycode:us', bias: 'countrycode:us' } ) ) assert_match(/bias=countrycode%3Aus/, url) assert_match(/filter=countrycode%3Aus/, url) assert_match(/type=amenity/, url) end def test_geoapify_reverse_query_url_contains_lat_lon lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( [45.423733, -75.676333] ) ) assert_match(/lat=45\.423733/, url) assert_match(/lon=-75\.676333/, url) end def test_geoapify_query_url_contains_autocomplete lookup = Geocoder::Lookup::Geoapify.new url = lookup.query_url( Geocoder::Query.new( 'Test Query', autocomplete: true ) ) assert_match(/\/geocode\/autocomplete/, url) end def test_geoapify_invalid_request Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest do Geocoder.search('invalid request') end end def test_geoapify_invalid_key Geocoder.configure(always_raise: [Geocoder::RequestDenied]) assert_raises Geocoder::RequestDenied do Geocoder.search('invalid key') end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/freegeoip_test.rb
test/unit/lookups/freegeoip_test.rb
# encoding: utf-8 require 'test_helper' class FreegeoipTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :freegeoip) end def test_result_on_ip_address_search result = Geocoder.search("74.200.247.59").first assert result.is_a?(Geocoder::Result::Freegeoip) end def test_result_on_loopback_ip_address_search result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal 'RD', result.country_code assert_equal "Reserved", result.country end def test_result_on_private_ip_address_search result = Geocoder.search("172.19.0.1").first assert_equal "172.19.0.1", result.ip assert_equal 'RD', result.country_code assert_equal "Reserved", result.country end def test_result_components result = Geocoder.search("74.200.247.59").first assert_equal "Plano, TX 75093, United States", result.address end def test_host_config Geocoder.configure(freegeoip: {host: "local.com"}) lookup = Geocoder::Lookup::Freegeoip.new query = Geocoder::Query.new("24.24.24.23") assert_match %r(https://local\.com), lookup.query_url(query) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/pointpin_test.rb
test/unit/lookups/pointpin_test.rb
# encoding: utf-8 require 'test_helper' class PointpinTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :pointpin, api_key: "abc123") end def test_result_on_ip_address_search result = Geocoder.search("80.111.55.55").first assert result.is_a?(Geocoder::Result::Pointpin) end def test_result_on_loopback_ip_address_search results = Geocoder.search("127.0.0.1") assert_equal 0, results.length end def test_result_on_private_ip_address_search results = Geocoder.search("172.19.0.1") assert_equal 0, results.length end def test_result_components result = Geocoder.search("80.111.55.55").first assert_equal "Dublin, Dublin City, 8, Ireland", result.address end def test_no_results silence_warnings do results = Geocoder.search("8.8.8.8") assert_equal 0, results.length end end def test_invalid_address silence_warnings do results = Geocoder.search("555.555.555.555", ip_address: true) assert_equal 0, results.length end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/geoportail_lu_test.rb
test/unit/lookups/geoportail_lu_test.rb
# encoding: utf-8 require 'test_helper' class GeoportailLuTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :geoportail_lu) end def test_query_for_geocode query = Geocoder::Query.new('55 route de luxembourg, pontpierre') lookup = Geocoder::Lookup.get(:geoportail_lu) res = lookup.query_url(query) assert_equal 'https://api.geoportail.lu/geocoder/search?queryString=55+route+de+luxembourg%2C+pontpierre', res end def test_query_for_reverse_geocode query = Geocoder::Query.new([45.423733, -75.676333]) lookup = Geocoder::Lookup.get(:geoportail_lu) res = lookup.query_url(query) assert_equal 'https://api.geoportail.lu/geocoder/reverseGeocode?lat=45.423733&lon=-75.676333', res end def test_results_component result = Geocoder.search('2 boulevard Royal, luxembourg').first assert_equal '2449', result.postal_code assert_equal 'Luxembourg', result.country assert_equal '2 Boulevard Royal,2449 Luxembourg', result.address assert_equal '2', result.street_number assert_equal 'Boulevard Royal', result.street assert_equal '2 Boulevard Royal', result.street_address assert_equal 'Luxembourg', result.city assert_equal 'Luxembourg', result.state assert_country_code result assert_equal(49.6146720749933, result.coordinates[0]) assert_equal(6.12939750216249, result.coordinates[1]) end def test_results_component_when_reverse_geocoding result = Geocoder.search([6.12476867352074, 49.6098566608772]).first assert_equal '1724', result.postal_code assert_equal 'Luxembourg', result.country assert_equal '39 Boulevard Prince Henri,1724 Luxembourg', result.address assert_equal '39', result.street_number assert_equal 'Boulevard Prince Henri', result.street assert_equal '39 Boulevard Prince Henri', result.street_address assert_equal 'Luxembourg', result.city assert_equal 'Luxembourg', result.state assert_country_code result assert_equal(49.6098566608772, result.coordinates[0]) assert_equal(6.12476867352074, result.coordinates[1]) end def test_no_results results = Geocoder.search('') assert_equal 0, results.length end private def assert_country_code(result) [:state_code, :country_code, :province_code].each do |method| assert_equal 'LU', result.send(method) end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/postcode_anywhere_uk_test.rb
test/unit/lookups/postcode_anywhere_uk_test.rb
# encoding: utf-8 require 'test_helper' class PostcodeAnywhereUkTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :postcode_anywhere_uk) set_api_key!(:postcode_anywhere_uk) end def test_result_components_with_placename_search results = Geocoder.search('Romsey') assert_equal 1, results.size assert_equal 'Romsey, Hampshire', results.first.address assert_equal 'SU 35270 21182', results.first.os_grid assert_equal [50.9889, -1.4989], results.first.coordinates assert_equal 'Romsey', results.first.city end def test_result_components_with_postcode results = Geocoder.search('WR26NJ') assert_equal 1, results.size assert_equal 'Moseley Road, Hallow, Worcester', results.first.address assert_equal 'SO 81676 59425', results.first.os_grid assert_equal [52.2327, -2.2697], results.first.coordinates assert_equal 'Hallow', results.first.city end def test_result_components_with_county results = Geocoder.search('hampshire') assert_equal 1, results.size assert_equal 'Hampshire', results.first.address assert_equal 'SU 48701 26642', results.first.os_grid assert_equal [51.037, -1.3068], results.first.coordinates assert_equal '', results.first.city end def test_no_results assert_equal [], Geocoder.search('no results') end def test_key_limit_exceeded_error Geocoder.configure(always_raise: [Geocoder::OverQueryLimitError]) assert_raises Geocoder::OverQueryLimitError do Geocoder.search('key limit exceeded') end end def test_unknown_key_error Geocoder.configure(always_raise: [Geocoder::InvalidApiKey]) assert_raises Geocoder::InvalidApiKey do Geocoder.search('unknown key') end end def test_generic_error Geocoder.configure(always_raise: [Geocoder::Error]) exception = assert_raises(Geocoder::Error) do Geocoder.search('generic error') end assert_equal 'A generic error occured.', exception.message end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipstack_test.rb
test/unit/lookups/ipstack_test.rb
# encoding: utf-8 require 'test_helper' class SpyLogger def initialize @log = [] end def logged?(msg) @log.include?(msg) end def add(level, msg) @log << msg end end class IpstackTest < GeocoderTestCase def setup super @logger = SpyLogger.new Geocoder.configure( :api_key => '123', :ip_lookup => :ipstack, :always_raise => :all, :logger => @logger ) end def test_result_on_ip_address_search result = Geocoder.search("134.201.250.155").first assert result.is_a?(Geocoder::Result::Ipstack) end def test_result_components result = Geocoder.search("134.201.250.155").first assert_equal "Los Angeles, CA 90013, United States", result.address end def test_all_top_level_api_fields result = Geocoder.search("134.201.250.155").first assert_equal "134.201.250.155", result.ip assert_equal "134.201.250.155", result.hostname assert_equal "NA", result.continent_code assert_equal "North America", result.continent_name assert_equal "US", result.country_code assert_equal "United States", result.country_name assert_equal "CA", result.region_code assert_equal "California", result.region_name assert_equal "Los Angeles", result.city assert_equal "90013", result.zip assert_equal 34.0453, result.latitude assert_equal (-118.2413), result.longitude end def test_nested_api_fields result = Geocoder.search("134.201.250.155").first assert result.location.is_a?(Hash) assert_equal 5368361, result.location['geoname_id'] assert result.time_zone.is_a?(Hash) assert_equal "America/Los_Angeles", result.time_zone['id'] assert result.currency.is_a?(Hash) assert_equal "USD", result.currency['code'] assert result.connection.is_a?(Hash) assert_equal 25876, result.connection['asn'] assert result.security.is_a?(Hash) end def test_required_base_fields result = Geocoder.search("134.201.250.155").first assert_equal "California", result.state assert_equal "CA", result.state_code assert_equal "United States", result.country assert_equal "90013", result.postal_code assert_equal [34.0453, -118.2413], result.coordinates end def test_logs_deprecation_of_metro_code_field result = Geocoder.search("134.201.250.155").first result.metro_code assert @logger.logged?("Ipstack does not implement `metro_code` in api results. Please discontinue use.") end def test_localhost_loopback result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal "RD", result.country_code assert_equal "Reserved", result.country_name end def test_localhost_loopback_defaults result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal "", result.hostname assert_equal "", result.continent_code assert_equal "", result.continent_name assert_equal "RD", result.country_code assert_equal "Reserved", result.country_name assert_equal "", result.region_code assert_equal "", result.region_name assert_equal "", result.city assert_equal "", result.zip assert_equal 0, result.latitude assert_equal 0, result.longitude assert_equal({}, result.location) assert_equal({}, result.time_zone) assert_equal({}, result.currency) assert_equal({}, result.connection) end def test_localhost_private result = Geocoder.search("172.19.0.1").first assert_equal "172.19.0.1", result.ip assert_equal "RD", result.country_code assert_equal "Reserved", result.country_name end def test_api_request_adds_access_key lookup = Geocoder::Lookup.get(:ipstack) assert_match 'https://api.ipstack.com/74.200.247.59?access_key=123', lookup.query_url(Geocoder::Query.new("74.200.247.59")) end def test_api_request_adds_security_when_specified lookup = Geocoder::Lookup.get(:ipstack) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { security: '1' })) assert_match(/&security=1/, query_url) end def test_api_request_adds_hostname_when_specified lookup = Geocoder::Lookup.get(:ipstack) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { hostname: '1' })) assert_match(/&hostname=1/, query_url) end def test_api_request_adds_language_when_specified lookup = Geocoder::Lookup.get(:ipstack) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { language: 'es' })) assert_match(/&language=es/, query_url) end def test_api_request_adds_fields_when_specified lookup = Geocoder::Lookup.get(:ipstack) query_url = lookup.query_url(Geocoder::Query.new("74.200.247.59", params: { fields: 'foo,bar' })) assert_match(/&fields=foo%2Cbar/, query_url) end def test_logs_warning_when_errors_are_set_not_to_raise Geocoder::Configuration.instance.data.clear Geocoder::Configuration.set_defaults Geocoder.configure(api_key: '123', ip_lookup: :ipstack, logger: @logger) lookup = Geocoder::Lookup.get(:ipstack) lookup.send(:results, Geocoder::Query.new("not_found")) assert @logger.logged?("Ipstack Geocoding API error: The requested resource does not exist.") end def test_uses_lookup_specific_configuration Geocoder::Configuration.instance.data.clear Geocoder::Configuration.set_defaults Geocoder.configure(api_key: '123', ip_lookup: :ipstack, logger: @logger, ipstack: { api_key: '345'}) lookup = Geocoder::Lookup.get(:ipstack) assert_match 'https://api.ipstack.com/74.200.247.59?access_key=345', lookup.query_url(Geocoder::Query.new("74.200.247.59")) end def test_not_authorized lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::InvalidRequest do lookup.send(:results, Geocoder::Query.new("not_found")) end assert_equal error.message, "The requested resource does not exist." end def test_missing_access_key lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::InvalidApiKey do lookup.send(:results, Geocoder::Query.new("missing_access_key")) end assert_equal error.message, "No API Key was specified." end def test_invalid_access_key lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::InvalidApiKey do lookup.send(:results, Geocoder::Query.new("invalid_access_key")) end assert_equal error.message, "No API Key was specified or an invalid API Key was specified." end def test_inactive_user lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::Error do lookup.send(:results, Geocoder::Query.new("inactive_user")) end assert_equal error.message, "The current user account is not active. User will be prompted to get in touch with Customer Support." end def test_invalid_api_function lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::InvalidRequest do lookup.send(:results, Geocoder::Query.new("invalid_api_function")) end assert_equal error.message, "The requested API endpoint does not exist." end def test_usage_limit lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::OverQueryLimitError do lookup.send(:results, Geocoder::Query.new("usage_limit")) end assert_equal error.message, "The maximum allowed amount of monthly API requests has been reached." end def test_access_restricted lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::RequestDenied do lookup.send(:results, Geocoder::Query.new("access_restricted")) end assert_equal error.message, "The current subscription plan does not support this API endpoint." end def test_protocol_access_restricted lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::RequestDenied do lookup.send(:results, Geocoder::Query.new("protocol_access_restricted")) end assert_equal error.message, "The user's current subscription plan does not support HTTPS Encryption." end def test_invalid_fields lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::InvalidRequest do lookup.send(:results, Geocoder::Query.new("invalid_fields")) end assert_equal error.message, "One or more invalid fields were specified using the fields parameter." end def test_too_many_ips lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::InvalidRequest do lookup.send(:results, Geocoder::Query.new("too_many_ips")) end assert_equal error.message, "Too many IPs have been specified for the Bulk Lookup Endpoint. (max. 50)" end def test_batch_not_supported lookup = Geocoder::Lookup.get(:ipstack) error = assert_raise Geocoder::RequestDenied do lookup.send(:results, Geocoder::Query.new("batch_not_supported")) end assert_equal error.message, "The Bulk Lookup Endpoint is not supported on the current subscription plan" end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipbase_test.rb
test/unit/lookups/ipbase_test.rb
# encoding: utf-8 require 'test_helper' class IpbaseTest < GeocoderTestCase def setup super Geocoder.configure(ip_lookup: :ipbase, lookup: :ipbase) end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_no_data results = Geocoder.search("no data") assert_equal 0, results.length end def test_invalid_ip results = Geocoder.search("invalid ip") assert_equal 0, results.length end def test_result_on_ip_address_search result = Geocoder.search("74.200.247.59").first assert result.is_a?(Geocoder::Result::Ipbase) end def test_result_on_loopback_ip_address_search result = Geocoder.search("127.0.0.1").first assert_equal "127.0.0.1", result.ip assert_equal 'RD', result.country_code assert_equal "Reserved", result.country end def test_result_on_private_ip_address_search result = Geocoder.search("172.19.0.1").first assert_equal "172.19.0.1", result.ip assert_equal 'RD', result.country_code assert_equal "Reserved", result.country end def test_result_components result = Geocoder.search("74.200.247.59").first assert_equal "Jersey City, New Jersey 07302, United States", result.address end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/postcodes_io_test.rb
test/unit/lookups/postcodes_io_test.rb
# encoding: utf-8 require 'test_helper' class PostcodesIoTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :postcodes_io) end def test_result_on_postcode_search results = Geocoder.search('WR26NJ') assert_equal 1, results.size assert_equal 'Worcestershire', results.first.county assert_equal [52.2327158260535, -2.26972239639173], results.first.coordinates end def test_no_results assert_equal [], Geocoder.search('no results') end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/here_test.rb
test/unit/lookups/here_test.rb
# encoding: utf-8 require 'test_helper' class HereTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :here) set_api_key!(:here) end def test_with_array_api_key_raises_when_configured Geocoder.configure(api_key: %w[foo bar]) Geocoder.configure(always_raise: :all) assert_raises(Geocoder::ConfigurationError) { Geocoder.search('berlin').first } end def test_here_viewport result = Geocoder.search('berlin').first assert_equal [52.33812, 13.08835, 52.6755, 13.761], result.viewport end def test_here_no_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [], result.viewport end def test_here_query_url_for_reverse_geocoding lookup = Geocoder::Lookup::Here.new url = lookup.query_url( Geocoder::Query.new( "42.42,21.21" ) ) expected = /revgeocode\.search\.hereapi\.com\/v1\/revgeocode.+at=42\.42%2C21\.21/ assert_match(expected, url) end def test_here_query_url_for_geocode lookup = Geocoder::Lookup::Here.new url = lookup.query_url( Geocoder::Query.new( "Madison Square Garden, New York, NY" ) ) expected = /geocode\.search\.hereapi\.com\/v1\/geocode.+q=Madison\+Square\+Garden%2C\+New\+York%2C\+NY/ assert_match(expected, url) end def test_here_query_url_contains_country lookup = Geocoder::Lookup::Here.new url = lookup.query_url( Geocoder::Query.new( 'Some Intersection', country: 'GBR' ) ) assert_match(/in=countryCode%3AGBR/, url) end def test_here_query_url_contains_api_key lookup = Geocoder::Lookup::Here.new url = lookup.query_url( Geocoder::Query.new( 'Some Intersection' ) ) assert_match(/apiKey=+/, url) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/osmnames_test.rb
test/unit/lookups/osmnames_test.rb
# encoding: utf-8 require 'test_helper' class OsmnamesTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :osmnames) set_api_key!(:osmnames) end def test_url_contains_api_key Geocoder.configure(osmnames: {api_key: 'abc123'}) query = Geocoder::Query.new('test') assert_includes query.url, 'key=abc123' end def test_url_contains_query_base query = Geocoder::Query.new("Madison Square Garden, New York, NY") assert_includes query.url, 'geocoder.tilehosting.com/q/Madison' end def test_url_contains_country_code query = Geocoder::Query.new("test", country_code: 'US') assert_includes query.url, 'https://geocoder.tilehosting.com/us/q/' end def test_result_components result = Geocoder.search('Madison Square Garden, New York, NY').first assert_equal [40.693073, -73.878418], result.coordinates assert_equal 'New York City, New York, United States of America', result.address assert_equal 'New York', result.state assert_equal 'New York City', result.city assert_equal 'us', result.country_code end def test_result_for_reverse_geocode result = Geocoder.search('-73.878418, 40.693073').first assert_equal 'New York City, New York, United States of America', result.address assert_equal 'New York', result.state assert_equal 'New York City', result.city assert_equal 'us', result.country_code end def test_url_for_reverse_geocode query = Geocoder::Query.new("-73.878418, 40.693073") assert_includes query.url, 'https://geocoder.tilehosting.com/r/-73.878418/40.693073.js' end def test_result_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.477398, -74.259087, 40.91618, -73.70018], result.viewport end def test_no_results assert_equal [], Geocoder.search("no results") end def test_raises_exception_when_return_message_error Geocoder.configure(always_raise: [Geocoder::InvalidRequest]) assert_raises Geocoder::InvalidRequest.new("Invalid attribute value.") do Geocoder.search("invalid request") end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/nominatim_test.rb
test/unit/lookups/nominatim_test.rb
# encoding: utf-8 require 'test_helper' class NominatimTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :nominatim) set_api_key!(:nominatim) end def test_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "10001", result.postal_code assert_nil result.city_district assert_nil result.state_district assert_nil result.neighbourhood assert_equal "Madison Square Garden, West 31st Street, Long Island City, New York City, New York, 10001, United States of America", result.address end def test_result_viewport result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal [40.749828338623, -73.9943389892578, 40.7511596679688, -73.9926528930664], result.viewport end def test_city_state_district result = Geocoder.search("cologne cathedral cologne germany").first assert_equal "Innenstadt", result.city_district assert_equal "Cologne Government Region", result.state_district end def test_neighbourhood result = Geocoder.search("cologne cathedral cologne germany").first assert_equal "Kunibertsviertel", result.neighbourhood end def test_host_configuration Geocoder.configure(nominatim: {host: "local.com"}) query = Geocoder::Query.new("Bluffton, SC") assert_match %r(https://local\.com), query.url end def test_raises_exception_when_over_query_limit Geocoder.configure(:always_raise => [Geocoder::OverQueryLimitError]) l = Geocoder::Lookup.get(:nominatim) assert_raises Geocoder::OverQueryLimitError do l.send(:results, Geocoder::Query.new("over limit")) end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/ipqualityscore_test.rb
test/unit/lookups/ipqualityscore_test.rb
# encoding: utf-8 require 'test_helper' class IpqualityscoreTest < GeocoderTestCase def setup super # configuring this IP lookup as the address lookup is weird, but necessary # in order to run tests with the 'quota exceeded' fixture Geocoder.configure(lookup: :ipqualityscore, ip_lookup: :ipqualityscore) set_api_key!(:ipqualityscore) end def test_result_attributes result = Geocoder.search('74.200.247.59').first # Request assert_equal('3YqddtowOADDvCm', result.request_id) assert_equal(true, result.success?) assert_equal('Success', result.message) # Geolocation assert_equal(40.73, result.latitude) assert_equal(-74.04, result.longitude) assert_equal 'Jersey City, New Jersey, US', result.address assert_equal('Jersey City', result.city) assert_equal('New Jersey', result.state) assert_equal('US', result.country_code) # Fallbacks for data API doesn't provide assert_equal('New Jersey', result.state_code) assert_equal('New Jersey', result.province_code) assert_equal('', result.postal_code) assert_equal('US', result.country) # Security assert_equal(false, result.mobile?) assert_equal(78, result.fraud_score) assert_equal('Rackspace Hosting', result.isp) assert_equal(19994, result.asn) assert_equal('Rackspace Hosting', result.organization) assert_equal(false, result.crawler?) assert_equal('74.200.247.59', result.host) assert_equal(true, result.proxy?) assert_equal(true, result.vpn?) assert_equal(false, result.tor?) assert_equal(false, result.active_vpn?) assert_equal(false, result.active_tor?) assert_equal(false, result.recent_abuse?) assert_equal(false, result.bot?) assert_equal('Corporate', result.connection_type) assert_equal('low', result.abuse_velocity) # Timezone assert_equal('America/New_York', result.timezone) end def test_raises_invalid_api_key_exception Geocoder.configure always_raise: :all assert_raises Geocoder::InvalidApiKey do Geocoder::Lookup::Ipqualityscore.new.send(:results, Geocoder::Query.new('invalid api key')) end end def test_raises_invalid_request_exception Geocoder.configure always_raise: :all assert_raises Geocoder::InvalidRequest do Geocoder::Lookup::Ipqualityscore.new.send(:results, Geocoder::Query.new('invalid request')) end end def test_raises_over_query_limit_exception_insufficient_credits Geocoder.configure always_raise: :all assert_raises Geocoder::OverQueryLimitError do Geocoder::Lookup::Ipqualityscore.new.send(:results, Geocoder::Query.new('insufficient credits')) end end def test_raises_over_query_limit_exception_quota_exceeded Geocoder.configure always_raise: :all assert_raises Geocoder::OverQueryLimitError do Geocoder::Lookup::Ipqualityscore.new.send(:results, Geocoder::Query.new('quota exceeded')) end end def test_unsuccessful_response_without_raising_does_not_hit_cache Geocoder.configure(cache: {}, always_raise: []) lookup = Geocoder::Lookup.get(:ipqualityscore) Geocoder.search('quota exceeded') assert_false lookup.instance_variable_get(:@cache_hit) Geocoder.search('quota exceeded') assert_false lookup.instance_variable_get(:@cache_hit) end def test_unsuccessful_response_with_raising_does_not_hit_cache Geocoder.configure(cache: {}, always_raise: [Geocoder::OverQueryLimitError]) lookup = Geocoder::Lookup.get(:ipqualityscore) assert_raises Geocoder::OverQueryLimitError do Geocoder.search('quota exceeded') end assert_false lookup.instance_variable_get(:@cache_hit) assert_raises Geocoder::OverQueryLimitError do Geocoder.search('quota exceeded') end assert_false lookup.instance_variable_get(:@cache_hit) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/smarty_streets_test.rb
test/unit/lookups/smarty_streets_test.rb
# encoding: utf-8 require 'test_helper' class SmartyStreetsTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :smarty_streets) set_api_key!(:smarty_streets) end def test_url_contains_api_key Geocoder.configure(:smarty_streets => {:api_key => 'blah'}) query = Geocoder::Query.new("Bluffton, SC") assert_match(/auth-token=blah/, query.url) end def test_query_for_address_geocode query = Geocoder::Query.new("42 Wallaby Way Sydney, AU") assert_match(/api\.smartystreets\.com\/street-address\?/, query.url) end def test_query_for_zipcode_geocode query = Geocoder::Query.new("22204") assert_match(/us-zipcode\.api\.smartystreets\.com\/lookup\?/, query.url) end def test_query_for_zipfour_geocode query = Geocoder::Query.new("22204-1603") assert_match(/us-zipcode\.api\.smartystreets\.com\/lookup\?/, query.url) end def test_query_for_international_geocode query = Geocoder::Query.new("13 rue yves toudic 75010", country: "France") assert_match(/international-street\.api\.smartystreets\.com\/verify\?/, query.url) end def test_smarty_streets_result_components result = Geocoder.search("Madison Square Garden, New York, NY").first assert_equal "Penn", result.street assert_equal "10121", result.zipcode assert_equal "1703", result.zip4 assert_equal "New York", result.city assert_equal "36061", result.fips assert_equal "US", result.country_code assert !result.zipcode_endpoint? end def test_smarty_streets_result_components_with_zipcode_only_query result = Geocoder.search("11211").first assert_equal "Brooklyn", result.city assert_equal "New York", result.state assert_equal "NY", result.state_code assert_equal "US", result.country_code assert result.zipcode_endpoint? end def test_smarty_streets_result_components_with_international_query result = Geocoder.search("13 rue yves toudic 75010", country: "France").first assert_equal 'Yves Toudic', result.street assert_equal 'Paris', result.city assert_equal '75010', result.postal_code assert_equal 'FRA', result.country_code assert result.international_endpoint? end def test_smarty_streets_when_longitude_latitude_does_not_exist result = Geocoder.search("96628").first assert_equal nil, result.coordinates end def test_no_results results = Geocoder.search("no results") assert_equal 0, results.length end def test_invalid_zipcode_returns_no_results assert_nothing_raised do assert_nil Geocoder.search("10300").first end end def test_raises_exception_on_error_http_status error_statuses = { '400' => Geocoder::InvalidRequest, '401' => Geocoder::RequestDenied, '402' => Geocoder::OverQueryLimitError } Geocoder.configure(always_raise: error_statuses.values) lookup = Geocoder::Lookup.get(:smarty_streets) error_statuses.each do |code, err| assert_raises err do response = MockHttpResponse.new(code: code.to_i) lookup.send(:check_response_for_errors!, response) end end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/test/unit/lookups/nationaal_georegister_nl_test.rb
test/unit/lookups/nationaal_georegister_nl_test.rb
# encoding: utf-8 require 'test_helper' class NationaalGeoregisterNlTest < GeocoderTestCase def setup super Geocoder.configure(lookup: :nationaal_georegister_nl) end def test_result_components result = Geocoder.search('Nieuwezijds Voorburgwal 147, Amsterdam').first assert_equal result.street, 'Nieuwezijds Voorburgwal' assert_equal result.street_number, '147' assert_equal result.city, 'Amsterdam' assert_equal result.postal_code, '1012RJ' assert_equal result.address, 'Nieuwezijds Voorburgwal 147, 1012RJ Amsterdam' assert_equal result.province, 'Noord-Holland' assert_equal result.province_code, 'PV27' assert_equal result.country_code, 'NL' assert_equal result.latitude, 52.37316397 assert_equal result.longitude, 4.89089949 end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/examples/cache_bypass.rb
examples/cache_bypass.rb
# This class allows you to configure how Geocoder should treat errors that occur when # the cache is not available. # Configure it like this # config/initializers/geocoder.rb # Geocoder.configure( # :cache => Geocoder::CacheBypass.new(Redis.new) # ) # # Depending on the value of @bypass this will either # raise the exception (true) or swallow it and pretend the cache did not return a hit (false) # class Geocoder::CacheBypass def initialize(target, bypass = true) @target = target @bypass = bypass end def [](key) with_bypass { @target[key] } end def []=(key, value) with_bypass(value) { @target[key] = value } end def keys with_bypass([]) { @target.keys } end def del(key) with_bypass { @target.del(key) } end private def with_bypass(return_value_if_exception = nil, &block) begin yield rescue if @bypass return_value_if_exception else raise # reraise original exception end end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/examples/app_defined_lookup_services.rb
examples/app_defined_lookup_services.rb
# To extend the Geocoder with additional lookups that come from the application, # not shipped with the gem, define a "child" lookup in your application, based on existing one. # This is required because the Geocoder::Configuration is a Singleton and stores one api key per lookup. # in app/libs/geocoder/lookup/my_preciousss.rb module Geocoder::Lookup class MyPreciousss < Google end end # Update Geocoder's street_services on initialize: # config/initializers/geocoder.rb Geocoder::Lookup.street_services << :my_preciousss # Override the configuration when necessary (e.g. provide separate Google API key for the account): Geocoder.configure(my_preciousss: { api_key: 'abcdef' }) # Lastly, search using your custom lookup service/api keys Geocoder.search("Paris", lookup: :my_preciousss) # This is useful when we have groups of users in the application who use Google paid services # and we want to properly separate them and allow using individual API KEYS or timeouts.
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/examples/reverse_geocode_job.rb
examples/reverse_geocode_job.rb
# This class implements an ActiveJob job for performing reverse-geocoding # asynchronously. Example usage: # if @location.save && @location.address.blank? # ReverseGeocodeJob.perform_later(@location) # end # Be sure to configure the queue adapter in config/application.rb: # config.active_job.queue_adapter = :sidekiq # You can read the Rails docs for more information on configuring ActiveJob: # http://edgeguides.rubyonrails.org/active_job_basics.html class ReverseGeocodeJob < ActiveJob::Base queue_as :high def perform(location) address = address(location) if address.present? location.update(address: address) end end private def address(location) Geocoder.address(location.coordinates) rescue => exception MonitoringService.notify(exception, location: { id: location.id }) if retryable?(exception) raise exception end end def retryable?(exception) exception.is_a?(Timeout::Error) || exception.is_a?(SocketError) end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/geocoder.rb
lib/geocoder.rb
require "geocoder/configuration" require "geocoder/logger" require "geocoder/kernel_logger" require "geocoder/query" require "geocoder/calculations" require "geocoder/exceptions" require "geocoder/cache" require "geocoder/request" require "geocoder/lookup" require "geocoder/ip_address" require "geocoder/models/active_record" if defined?(::ActiveRecord) require "geocoder/models/mongoid" if defined?(::Mongoid) require "geocoder/models/mongo_mapper" if defined?(::MongoMapper) module Geocoder ## # Search for information about an address or a set of coordinates. # def self.search(query, options = {}) query = Geocoder::Query.new(query, options) unless query.is_a?(Geocoder::Query) query.blank? ? [] : query.execute end ## # Look up the coordinates of the given street or IP address. # def self.coordinates(address, options = {}) if (results = search(address, options)).size > 0 results.first.coordinates end end ## # Look up the address of the given coordinates ([lat,lon]) # or IP address (string). # def self.address(query, options = {}) if (results = search(query, options)).size > 0 results.first.address end end end # load Railtie if Rails exists if defined?(Rails) require "geocoder/railtie" end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/easting_northing.rb
lib/easting_northing.rb
module Geocoder class EastingNorthing attr_reader :easting, :northing, :lat_lng def initialize(opts) @easting = opts[:easting] @northing = opts[:northing] @lat_lng = to_WGS84(to_osgb_36) end private def to_osgb_36 osgb_fo = 0.9996012717 northing0 = -100_000.0 easting0 = 400_000.0 phi0 = deg_to_rad(49.0) lambda0 = deg_to_rad(-2.0) a = 6_377_563.396 b = 6_356_256.909 eSquared = ((a * a) - (b * b)) / (a * a) phi = 0.0 lambda = 0.0 n = (a - b) / (a + b) m = 0.0 phiPrime = ((northing - northing0) / (a * osgb_fo)) + phi0 while (northing - northing0 - m) >= 0.001 m = (b * osgb_fo)\ * (((1 + n + ((5.0 / 4.0) * n * n) + ((5.0 / 4.0) * n * n * n))\ * (phiPrime - phi0))\ - (((3 * n) + (3 * n * n) + ((21.0 / 8.0) * n * n * n))\ * Math.sin(phiPrime - phi0)\ * Math.cos(phiPrime + phi0))\ + ((((15.0 / 8.0) * n * n) + ((15.0 / 8.0) * n * n * n))\ * Math.sin(2.0 * (phiPrime - phi0))\ * Math.cos(2.0 * (phiPrime + phi0)))\ - (((35.0 / 24.0) * n * n * n)\ * Math.sin(3.0 * (phiPrime - phi0))\ * Math.cos(3.0 * (phiPrime + phi0)))) phiPrime += (northing - northing0 - m) / (a * osgb_fo) end v = a * osgb_fo * ((1.0 - eSquared * sin_pow_2(phiPrime))**-0.5) rho = a\ * osgb_fo\ * (1.0 - eSquared)\ * ((1.0 - eSquared * sin_pow_2(phiPrime))**-1.5) etaSquared = (v / rho) - 1.0 vii = Math.tan(phiPrime) / (2 * rho * v) viii = (Math.tan(phiPrime) / (24.0 * rho * (v**3.0)))\ * (5.0\ + (3.0 * tan_pow_2(phiPrime))\ + etaSquared\ - (9.0 * tan_pow_2(phiPrime) * etaSquared)) ix = (Math.tan(phiPrime) / (720.0 * rho * (v**5.0)))\ * (61.0\ + (90.0 * tan_pow_2(phiPrime))\ + (45.0 * tan_pow_2(phiPrime) * tan_pow_2(phiPrime))) x = sec(phiPrime) / v xi = (sec(phiPrime) / (6.0 * v * v * v))\ * ((v / rho) + (2 * tan_pow_2(phiPrime))) xiii = (sec(phiPrime) / (120.0 * (v**5.0)))\ * (5.0\ + (28.0 * tan_pow_2(phiPrime))\ + (24.0 * tan_pow_2(phiPrime) * tan_pow_2(phiPrime))) xiia = (sec(phiPrime) / (5040.0 * (v**7.0)))\ * (61.0\ + (662.0 * tan_pow_2(phiPrime))\ + (1320.0 * tan_pow_2(phiPrime) * tan_pow_2(phiPrime))\ + (720.0\ * tan_pow_2(phiPrime)\ * tan_pow_2(phiPrime)\ * tan_pow_2(phiPrime))) phi = phiPrime\ - (vii * ((easting - easting0)**2.0))\ + (viii * ((easting - easting0)**4.0))\ - (ix * ((easting - easting0)**6.0)) lambda = lambda0\ + (x * (easting - easting0))\ - (xi * ((easting - easting0)**3.0))\ + (xiii * ((easting - easting0)**5.0))\ - (xiia * ((easting - easting0)**7.0)) [rad_to_deg(phi), rad_to_deg(lambda)] end def to_WGS84(latlng) latitude = latlng[0] longitude = latlng[1] a = 6_377_563.396 b = 6_356_256.909 eSquared = ((a * a) - (b * b)) / (a * a) phi = deg_to_rad(latitude) lambda = deg_to_rad(longitude) v = a / Math.sqrt(1 - eSquared * sin_pow_2(phi)) h = 0 x = (v + h) * Math.cos(phi) * Math.cos(lambda) y = (v + h) * Math.cos(phi) * Math.sin(lambda) z = ((1 - eSquared) * v + h) * Math.sin(phi) tx = 446.448 ty = -124.157 tz = 542.060 s = -0.0000204894 rx = deg_to_rad(0.00004172222) ry = deg_to_rad(0.00006861111) rz = deg_to_rad(0.00023391666) xB = tx + (x * (1 + s)) + (-rx * y) + (ry * z) yB = ty + (rz * x) + (y * (1 + s)) + (-rx * z) zB = tz + (-ry * x) + (rx * y) + (z * (1 + s)) a = 6_378_137.000 b = 6_356_752.3141 eSquared = ((a * a) - (b * b)) / (a * a) lambdaB = rad_to_deg(Math.atan(yB / xB)) p = Math.sqrt((xB * xB) + (yB * yB)) phiN = Math.atan(zB / (p * (1 - eSquared))) (1..10).each do |_i| v = a / Math.sqrt(1 - eSquared * sin_pow_2(phiN)) phiN1 = Math.atan((zB + (eSquared * v * Math.sin(phiN))) / p) phiN = phiN1 end phiB = rad_to_deg(phiN) [phiB, lambdaB] end def deg_to_rad(degrees) degrees / 180.0 * Math::PI end def rad_to_deg(r) (r / Math::PI) * 180 end def sin_pow_2(x) Math.sin(x) * Math.sin(x) end def cos_pow_2(x) Math.cos(x) * Math.cos(x) end def tan_pow_2(x) Math.tan(x) * Math.tan(x) end def sec(x) 1.0 / Math.cos(x) end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/maxmind_database.rb
lib/maxmind_database.rb
require 'csv' require 'net/http' module Geocoder module MaxmindDatabase extend self def download(package, dir = "tmp") filepath = File.expand_path(File.join(dir, "#{archive_edition(package)}.zip")) open(filepath, 'wb') do |file| uri = URI.parse(base_url(package)) Net::HTTP.start(uri.host, uri.port) do |http| http.request_get(uri.path) do |resp| # TODO: show progress resp.read_body do |segment| file.write(segment) end end end end end def insert(package, dir = "tmp") data_files(package, dir).each do |filepath,table| print "Resetting table #{table}..." ActiveRecord::Base.connection.execute("DELETE FROM #{table}") puts "done" insert_into_table(table, filepath) end end def archive_filename(package) p = archive_url_path(package) s = !(pos = p.rindex('/')).nil? && pos + 1 || 0 p[s..-1] end def archive_edition(package) { geolite_country_csv: "GeoLite2-Country-CSV", geolite_city_csv: "GeoLite2-City-CSV", geolite_asn_csv: "GeoLite2-ASN-CSV" }[package] end private # ------------------------------------------------------------- def table_columns(table_name) { maxmind_geolite_city_blocks: %w[start_ip_num end_ip_num loc_id], maxmind_geolite_city_location: %w[loc_id country region city postal_code latitude longitude metro_code area_code], maxmind_geolite_country: %w[start_ip end_ip start_ip_num end_ip_num country_code country] }[table_name.to_sym] end def insert_into_table(table, filepath) start_time = Time.now print "Loading data for table #{table}" rows = [] columns = table_columns(table) CSV.foreach(filepath, encoding: "ISO-8859-1") do |line| # Some files have header rows. # skip if starts with "Copyright" or "locId" or "startIpNum" next if line.first.match(/[A-z]/) rows << line.to_a if rows.size == 10000 insert_rows(table, columns, rows) rows = [] print "." end end insert_rows(table, columns, rows) if rows.size > 0 puts "done (#{Time.now - start_time} seconds)" end def insert_rows(table, headers, rows) value_strings = rows.map do |row| "(" + row.map{ |col| sql_escaped_value(col) }.join(',') + ")" end q = "INSERT INTO #{table} (#{headers.join(',')}) " + "VALUES #{value_strings.join(',')}" ActiveRecord::Base.connection.execute(q) end def sql_escaped_value(value) value.to_i.to_s == value ? value : ActiveRecord::Base.connection.quote(value) end def data_files(package, dir = "tmp") case package when :geolite_city_csv # use the last two in case multiple versions exist files = Dir.glob(File.join(dir, "GeoLiteCity_*/*.csv"))[-2..-1].sort Hash[*files.zip(["maxmind_geolite_city_blocks", "maxmind_geolite_city_location"]).flatten] when :geolite_country_csv {File.join(dir, "GeoIPCountryWhois.csv") => "maxmind_geolite_country"} end end def archive_url(package) base_url + archive_url_path(package) end def base_url(edition) "https://download.maxmind.com/app/geoip_download?edition_id=#{edition}&license_key=#{ENV['LICENSE_KEY']}&suffix=zip" end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/migration_version.rb
lib/generators/geocoder/migration_version.rb
module Geocoder module Generators module MigrationVersion def rails_5? Rails::VERSION::MAJOR == 5 end def migration_version if rails_5? "[#{Rails::VERSION::MAJOR}.#{Rails::VERSION::MINOR}]" end end end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/maxmind/geolite_country_generator.rb
lib/generators/geocoder/maxmind/geolite_country_generator.rb
require 'rails/generators/migration' require 'generators/geocoder/migration_version' module Geocoder module Generators module Maxmind class GeoliteCountryGenerator < Rails::Generators::Base include Rails::Generators::Migration include Generators::MigrationVersion source_root File.expand_path('../templates', __FILE__) def copy_migration_files migration_template "migration/geolite_country.rb", "db/migrate/geocoder_maxmind_geolite_country.rb" end # Define the next_migration_number method (necessary for the # migration_template method to work) def self.next_migration_number(dirname) if ActiveRecord::Base.timestamped_migrations sleep 1 # make sure each time we get a different timestamp Time.new.utc.strftime("%Y%m%d%H%M%S") else "%.3d" % (current_migration_number(dirname) + 1) end end end end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/maxmind/geolite_city_generator.rb
lib/generators/geocoder/maxmind/geolite_city_generator.rb
require 'rails/generators/migration' require 'generators/geocoder/migration_version' module Geocoder module Generators module Maxmind class GeoliteCityGenerator < Rails::Generators::Base include Rails::Generators::Migration include Generators::MigrationVersion source_root File.expand_path('../templates', __FILE__) def copy_migration_files migration_template "migration/geolite_city.rb", "db/migrate/geocoder_maxmind_geolite_city.rb" end # Define the next_migration_number method (necessary for the # migration_template method to work) def self.next_migration_number(dirname) if ActiveRecord::Base.timestamped_migrations sleep 1 # make sure each time we get a different timestamp Time.new.utc.strftime("%Y%m%d%H%M%S") else "%.3d" % (current_migration_number(dirname) + 1) end end end end end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/maxmind/templates/migration/geolite_city.rb
lib/generators/geocoder/maxmind/templates/migration/geolite_city.rb
class GeocoderMaxmindGeoliteCity < ActiveRecord::Migration<%= migration_version %> def self.up create_table :maxmind_geolite_city_blocks, id: false do |t| t.column :start_ip_num, :bigint, null: false t.column :end_ip_num, :bigint, null: false t.column :loc_id, :bigint, null: false end add_index :maxmind_geolite_city_blocks, :loc_id add_index :maxmind_geolite_city_blocks, :start_ip_num, unique: true add_index :maxmind_geolite_city_blocks, [:end_ip_num, :start_ip_num], unique: true, name: 'index_maxmind_geolite_city_blocks_on_end_ip_num_range' create_table :maxmind_geolite_city_location, id: false do |t| t.column :loc_id, :bigint, null: false t.string :country, null: false t.string :region, null: false t.string :city t.string :postal_code, null: false t.float :latitude t.float :longitude t.integer :metro_code t.integer :area_code end add_index :maxmind_geolite_city_location, :loc_id, unique: true end def self.down drop_table :maxmind_geolite_city_location drop_table :maxmind_geolite_city_blocks end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false
alexreisner/geocoder
https://github.com/alexreisner/geocoder/blob/8143fce1820539cdaf6344c3400edf5690ec1611/lib/generators/geocoder/maxmind/templates/migration/geolite_country.rb
lib/generators/geocoder/maxmind/templates/migration/geolite_country.rb
class GeocoderMaxmindGeoliteCountry < ActiveRecord::Migration<%= migration_version %> def self.up create_table :maxmind_geolite_country, id: false do |t| t.column :start_ip, :string t.column :end_ip, :string t.column :start_ip_num, :bigint, null: false t.column :end_ip_num, :bigint, null: false t.column :country_code, :string, null: false t.column :country, :string, null: false end add_index :maxmind_geolite_country, :start_ip_num, unique: true end def self.down drop_table :maxmind_geolite_country end end
ruby
MIT
8143fce1820539cdaf6344c3400edf5690ec1611
2026-01-04T15:40:27.673533Z
false