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
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/kernel/singleton_class.rb
motion/core_ext/kernel/singleton_class.rb
module Kernel # class_eval on an object acts like singleton_class.class_eval. def class_eval(*args, &block) singleton_class.class_eval(*args, &block) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/range/include_range.rb
motion/core_ext/range/include_range.rb
class Range # Extends the default Range#include? to support range comparisons. # (1..5).include?(1..5) # => true # (1..5).include?(2..3) # => true # (1..5).include?(2..6) # => false # # The native Range#include? behavior is untouched. # ('a'..'f').include?('c') # => true # (5..9).include?(11) # => false def include_with_range?(value) if value.is_a?(::Range) # 1...10 includes 1..9 but it does not include 1..10. operator = exclude_end? && !value.exclude_end? ? :< : :<= include_without_range?(value.first) && value.last.send(operator, last) else include_without_range?(value) end end alias_method_chain :include?, :range end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/range/overlaps.rb
motion/core_ext/range/overlaps.rb
class Range # Compare two ranges and see if they overlap each other # (1..5).overlaps?(4..6) # => true # (1..5).overlaps?(7..9) # => false def overlaps?(other) cover?(other.first) || other.cover?(first) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/time/conversions.rb
motion/core_ext/time/conversions.rb
class Time DATE_FORMATS = { :db => '%Y-%m-%d %H:%M:%S', :number => '%Y%m%d%H%M%S', :nsec => '%Y%m%d%H%M%S%9N', :time => '%H:%M', :short => '%d %b %H:%M', :long => '%B %d, %Y %H:%M', :long_ordinal => lambda { |time| day_format = MotionSupport::Inflector.ordinalize(time.day) time.strftime("%B #{day_format}, %Y %H:%M") }, :rfc822 => lambda { |time| offset_format = time.formatted_offset(false) time.strftime("%a, %d %b %Y %H:%M:%S #{offset_format}") }, :iso8601 => '%Y-%m-%dT%H:%M:%SZ' } # Accepts a iso8601 time string and returns a new instance of Time def self.iso8601(time_string) format_string = "yyyy-MM-dd'T'HH:mm:ss" # Fractional Seconds format_string += '.SSS' if time_string.include?('.') # Zulu (standard) or with a timezone format_string += time_string.include?('Z') ? "'Z'" : 'ZZZZZ' cached_date_formatter(format_string).dateFromString(time_string) end # Returns an iso8601-compliant string # This method is aliased to <tt>xmlschema</tt>. def iso8601 utc.strftime DATE_FORMATS[:iso8601] end alias_method :xmlschema, :iso8601 # Converts to a formatted string. See DATE_FORMATS for builtin formats. # # This method is aliased to <tt>to_s</tt>. # # time = Time.now # => Thu Jan 18 06:10:17 CST 2007 # # time.to_formatted_s(:time) # => "06:10" # time.to_s(:time) # => "06:10" # # time.to_formatted_s(:db) # => "2007-01-18 06:10:17" # time.to_formatted_s(:number) # => "20070118061017" # time.to_formatted_s(:short) # => "18 Jan 06:10" # time.to_formatted_s(:long) # => "January 18, 2007 06:10" # time.to_formatted_s(:long_ordinal) # => "January 18th, 2007 06:10" # time.to_formatted_s(:rfc822) # => "Thu, 18 Jan 2007 06:10:17 -0600" # # == Adding your own time formats to +to_formatted_s+ # You can add your own formats to the Time::DATE_FORMATS hash. # Use the format name as the hash key and either a strftime string # or Proc instance that takes a time argument as the value. # # # config/initializers/time_formats.rb # Time::DATE_FORMATS[:month_and_year] = '%B %Y' # Time::DATE_FORMATS[:short_ordinal] = ->(time) { time.strftime("%B #{time.day.ordinalize}") } def to_formatted_s(format = :default) return iso8601 if format == :iso8601 formatter = DATE_FORMATS[format] return to_default_s unless formatter return formatter.call(self).to_s if formatter.respond_to?(:call) strftime(formatter) end alias_method :to_default_s, :to_s alias_method :to_s, :to_formatted_s private def self.cached_date_formatter(dateFormat) Thread.current[:date_formatters] ||= {} Thread.current[:date_formatters][dateFormat] ||= NSDateFormatter.alloc.init.tap do |formatter| formatter.dateFormat = dateFormat formatter.timeZone = NSTimeZone.timeZoneWithAbbreviation 'UTC' end end private_class_method :cached_date_formatter end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/time/acts_like.rb
motion/core_ext/time/acts_like.rb
class Time # Duck-types as a Time-like class. See Object#acts_like?. def acts_like_time? true end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/time/calculations.rb
motion/core_ext/time/calculations.rb
class Time include DateAndTime::Calculations COMMON_YEAR_DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] class << self # Return the number of days in the given month. # If no year is specified, it will use the current year. def days_in_month(month, year = now.year) if month == 2 && ::Date.gregorian_leap?(year) 29 else COMMON_YEAR_DAYS_IN_MONTH[month] end end # Alias for <tt>Time.now</tt>. def current ::Time.now end end # Seconds since midnight: Time.now.seconds_since_midnight def seconds_since_midnight to_i - change(:hour => 0).to_i + (usec / 1.0e+6) end # Returns the number of seconds until 23:59:59. # # Time.new(2012, 8, 29, 0, 0, 0).seconds_until_end_of_day # => 86399 # Time.new(2012, 8, 29, 12, 34, 56).seconds_until_end_of_day # => 41103 # Time.new(2012, 8, 29, 23, 59, 59).seconds_until_end_of_day # => 0 def seconds_until_end_of_day end_of_day.to_i - to_i end # Returns a new Time where one or more of the elements have been changed according # to the +options+ parameter. The time options (<tt>:hour</tt>, <tt>:min</tt>, # <tt>:sec</tt>, <tt>:usec</tt>) reset cascadingly, so if only the hour is passed, # then minute, sec, and usec is set to 0. If the hour and minute is passed, then # sec and usec is set to 0. The +options+ parameter takes a hash with any of these # keys: <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>, <tt>:hour</tt>, <tt>:min</tt>, # <tt>:sec</tt>, <tt>:usec</tt>. # # Time.new(2012, 8, 29, 22, 35, 0).change(day: 1) # => Time.new(2012, 8, 1, 22, 35, 0) # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, day: 1) # => Time.new(1981, 8, 1, 22, 35, 0) # Time.new(2012, 8, 29, 22, 35, 0).change(year: 1981, hour: 0) # => Time.new(1981, 8, 29, 0, 0, 0) def change(options) new_year = options.fetch(:year, year) new_month = options.fetch(:month, month) new_day = options.fetch(:day, day) new_hour = options.fetch(:hour, hour) new_min = options.fetch(:min, options[:hour] ? 0 : min) new_sec = options.fetch(:sec, (options[:hour] || options[:min]) ? 0 : sec) new_usec = options.fetch(:usec, (options[:hour] || options[:min] || options[:sec]) ? 0 : Rational(nsec, 1000)) if utc? ::Time.utc(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec) elsif zone ::Time.local(new_year, new_month, new_day, new_hour, new_min, new_sec, new_usec) else ::Time.new(new_year, new_month, new_day, new_hour, new_min, new_sec + (new_usec.to_r / 1000000), utc_offset) end end # Uses Date to provide precise Time calculations for years, months, and days. # The +options+ parameter takes a hash with any of these keys: <tt>:years</tt>, # <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>, <tt>:hours</tt>, # <tt>:minutes</tt>, <tt>:seconds</tt>. def advance(options) unless options[:weeks].nil? options[:weeks], partial_weeks = options[:weeks].divmod(1) options[:days] = options.fetch(:days, 0) + 7 * partial_weeks end unless options[:days].nil? options[:days], partial_days = options[:days].divmod(1) options[:hours] = options.fetch(:hours, 0) + 24 * partial_days end d = to_date.advance(options) time_advanced_by_date = change(:year => d.year, :month => d.month, :day => d.day) seconds_to_advance = \ options.fetch(:seconds, 0) + options.fetch(:minutes, 0) * 60 + options.fetch(:hours, 0) * 3600 if seconds_to_advance.zero? time_advanced_by_date else time_advanced_by_date.since(seconds_to_advance) end end # Returns a new Time representing the time a number of seconds ago, this is basically a wrapper around the Numeric extension def ago(seconds) since(-seconds) end # Returns a new Time representing the time a number of seconds since the instance time def since(seconds) self + seconds rescue to_datetime.since(seconds) end alias :in :since # Returns a new Time representing the start of the day (0:00) def beginning_of_day #(self - seconds_since_midnight).change(usec: 0) change(:hour => 0) end alias :midnight :beginning_of_day alias :at_midnight :beginning_of_day alias :at_beginning_of_day :beginning_of_day # Returns a new Time representing the end of the day, 23:59:59.999999 (.999999999 in ruby1.9) def end_of_day change( :hour => 23, :min => 59, :sec => 59, :usec => Rational(999999999, 1000) ) end alias :at_end_of_day :end_of_day # Returns a new Time representing the start of the hour (x:00) def beginning_of_hour change(:min => 0) end alias :at_beginning_of_hour :beginning_of_hour # Returns a new Time representing the end of the hour, x:59:59.999999 (.999999999 in ruby1.9) def end_of_hour change( :min => 59, :sec => 59, :usec => Rational(999999999, 1000) ) end alias :at_end_of_hour :end_of_hour # Returns a new Time representing the start of the minute (x:xx:00) def beginning_of_minute change(:sec => 0) end alias :at_beginning_of_minute :beginning_of_minute # Returns a new Time representing the end of the minute, x:xx:59.999999 (.999999999 in ruby1.9) def end_of_minute change( :sec => 59, :usec => Rational(999999999, 1000) ) end alias :at_end_of_minute :end_of_minute # Returns a Range representing the whole day of the current time. def all_day beginning_of_day..end_of_day end # Returns a Range representing the whole week of the current time. # Week starts on start_day, default is <tt>Date.week_start</tt> or <tt>config.week_start</tt> when set. def all_week(start_day = Date.beginning_of_week) beginning_of_week(start_day)..end_of_week(start_day) end # Returns a Range representing the whole month of the current time. def all_month beginning_of_month..end_of_month end # Returns a Range representing the whole quarter of the current time. def all_quarter beginning_of_quarter..end_of_quarter end # Returns a Range representing the whole year of the current time. def all_year beginning_of_year..end_of_year end def plus_with_duration(other) #:nodoc: if MotionSupport::Duration === other other.since(self) else plus_without_duration(other) end end alias_method :plus_without_duration, :+ alias_method :+, :plus_with_duration def minus_with_duration(other) #:nodoc: if MotionSupport::Duration === other other.until(self) else minus_without_duration(other) end end alias_method :minus_without_duration, :- alias_method :-, :minus_with_duration # Layers additional behavior on Time#<=> so that Date instances # can be chronologically compared with a Time def compare_with_coercion(other) compare_without_coercion(other.to_time) end alias_method :compare_without_coercion, :<=> alias_method :<=>, :compare_with_coercion end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/to_json.rb
motion/core_ext/object/to_json.rb
# encoding: utf-8 class Object # Serializes the object to a hash then the hash using Cocoa's NSJSONSerialization def to_json attributes = if respond_to?(:to_hash) to_hash.as_json else instance_values.as_json end attributes.to_json end end class NilClass # Returns 'null'. def to_json 'null' end end class TrueClass # Returns +self+ as string. def to_json self.to_s end end class FalseClass # Returns +self+ as string. def to_json self.to_s end end class JSONString # JSON escape characters class << self ESCAPED_CHARS = { "\u0000" => '\u0000', "\u0001" => '\u0001', "\u0002" => '\u0002', "\u0003" => '\u0003', "\u0004" => '\u0004', "\u0005" => '\u0005', "\u0006" => '\u0006', "\u0007" => '\u0007', "\u0008" => '\b', "\u0009" => '\t', "\u000A" => '\n', "\u000B" => '\u000B', "\u000C" => '\f', "\u000D" => '\r', "\u000E" => '\u000E', "\u000F" => '\u000F', "\u0010" => '\u0010', "\u0011" => '\u0011', "\u0012" => '\u0012', "\u0013" => '\u0013', "\u0014" => '\u0014', "\u0015" => '\u0015', "\u0016" => '\u0016', "\u0017" => '\u0017', "\u0018" => '\u0018', "\u0019" => '\u0019', "\u001A" => '\u001A', "\u001B" => '\u001B', "\u001C" => '\u001C', "\u001D" => '\u001D', "\u001E" => '\u001E', "\u001F" => '\u001F', "\u2028" => '\u2028', "\u2029" => '\u2029', '"' => '\"', '\\' => '\\\\', '>' => '\u003E', '<' => '\u003C', '&' => '\u0026'} ESCAPE_REGEX = /[\u0000-\u001F\u2028\u2029"\\><&]/u def escape(string) %("#{string.gsub ESCAPE_REGEX, ESCAPED_CHARS}") end end end class String # Returns JSON-escaped +self+. def to_json JSONString.escape(self) end end class Symbol # Returns +self+ as string. def to_json self.to_s end end class Numeric # Returns +self+. def to_json self end end class Date def as_json strftime("%Y-%m-%d") end def to_json as_json.to_json end end class Time def as_json xmlschema end def to_json as_json.to_json end end # For more complex objects (Array/Hash): # Convert an object into a "JSON-ready" representation composed of # primitives like Hash, Array, String, Numeric, and true/false/nil. # Recursively calls #as_json to the object to recursively build a # fully JSON-ready object. # # This allows developers to implement #as_json without having to # worry about what base types of objects they are allowed to return # or having to remember to call #as_json recursively. class Array def as_json map { |v| (v.respond_to?(:as_json) ? v.as_json : v) } end # Calls <tt>as_json</tt> on all its elements and converts to a string. def to_json NSJSONSerialization.dataWithJSONObject(as_json, options: 0, error: nil).to_s end end class Hash # Ensure there are valid keys/values def as_json Hash[map { |k,v| [k.to_s, (v.respond_to?(:as_json) ? v.as_json : v)] }] end # Serializes the hash object using Cocoa's NSJSONSerialization def to_json # JSON keys must be strings, and any sub-objects also serialized NSJSONSerialization.dataWithJSONObject(as_json, options: 0, error: nil).to_s end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/instance_variables.rb
motion/core_ext/object/instance_variables.rb
class Object # Returns a hash with string keys that maps instance variable names without "@" to their # corresponding values. # # class C # def initialize(x, y) # @x, @y = x, y # end # end # # C.new(0, 1).instance_values # => {"x" => 0, "y" => 1} def instance_values Hash[instance_variables.map { |name| [name[1..-1], instance_variable_get(name)] }] end # Returns an array of instance variable names as strings including "@". # # class C # def initialize(x, y) # @x, @y = x, y # end # end # # C.new(0, 1).instance_variable_names # => ["@y", "@x"] def instance_variable_names instance_variables.map { |var| var.to_s } end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/duplicable.rb
motion/core_ext/object/duplicable.rb
#-- # Most objects are cloneable, but not all. For example you can't dup +nil+: # # nil.dup # => TypeError: can't dup NilClass # # Classes may signal their instances are not duplicable removing +dup+/+clone+ # or raising exceptions from them. So, to dup an arbitrary object you normally # use an optimistic approach and are ready to catch an exception, say: # # arbitrary_object.dup rescue object # # Rails dups objects in a few critical spots where they are not that arbitrary. # That rescue is very expensive (like 40 times slower than a predicate), and it # is often triggered. # # That's why we hardcode the following cases and check duplicable? instead of # using that rescue idiom. #++ class Object # Can you safely dup this object? # # False for +nil+, +false+, +true+, symbol, and number objects; # true otherwise. def duplicable? true end end class NilClass # +nil+ is not duplicable: # # nil.duplicable? # => false # nil.dup # => TypeError: can't dup NilClass def duplicable? false end end class FalseClass # +false+ is not duplicable: # # false.duplicable? # => false # false.dup # => TypeError: can't dup FalseClass def duplicable? false end end class TrueClass # +true+ is not duplicable: # # true.duplicable? # => false # true.dup # => TypeError: can't dup TrueClass def duplicable? false end end class Symbol # Symbols are not duplicable: # # :my_symbol.duplicable? # => false # :my_symbol.dup # => TypeError: can't dup Symbol def duplicable? false end end class Numeric # Numbers are not duplicable: # # 3.duplicable? # => false # 3.dup # => TypeError: can't dup Fixnum def duplicable? false end end class BigDecimal def duplicable? false end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/to_param.rb
motion/core_ext/object/to_param.rb
class Object # Alias of <tt>to_s</tt>. def to_param to_s end end class NilClass # Returns +self+. def to_param self end end class TrueClass # Returns +self+. def to_param self end end class FalseClass # Returns +self+. def to_param self end end class Array # Calls <tt>to_param</tt> on all its elements and joins the result with # slashes. This is used by <tt>url_for</tt> in Action Pack. def to_param collect { |e| e.to_param }.join '/' end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/blank.rb
motion/core_ext/object/blank.rb
# encoding: utf-8 class Object # An object is blank if it's false, empty, or a whitespace string. # For example, '', ' ', +nil+, [], and {} are all blank. # # This simplifies: # # if address.nil? || address.empty? # # ...to: # # if address.blank? def blank? respond_to?(:empty?) ? empty? : !self end # An object is present if it's not <tt>blank?</tt>. def present? !blank? end # Returns object if it's <tt>present?</tt> otherwise returns +nil+. # <tt>object.presence</tt> is equivalent to <tt>object.present? ? object : nil</tt>. # # This is handy for any representation of objects where blank is the same # as not present at all. For example, this simplifies a common check for # HTTP POST/query parameters: # # state = params[:state] if params[:state].present? # country = params[:country] if params[:country].present? # region = state || country || 'US' # # ...becomes: # # region = params[:state].presence || params[:country].presence || 'US' def presence self if present? end end class NilClass # +nil+ is blank: # # nil.blank? # => true def blank? true end end class FalseClass # +false+ is blank: # # false.blank? # => true def blank? true end end class TrueClass # +true+ is not blank: # # true.blank? # => false def blank? false end end class Array # An array is blank if it's empty: # # [].blank? # => true # [1,2,3].blank? # => false alias_method :blank?, :empty? end class Hash # A hash is blank if it's empty: # # {}.blank? # => true # { key: 'value' }.blank? # => false alias_method :blank?, :empty? end class String # A string is blank if it's empty or contains whitespaces only: # # ''.blank? # => true # ' '.blank? # => true # ' '.blank? # => true # ' something here '.blank? # => false def blank? self !~ /[^[:space:]]/ end end class Numeric #:nodoc: # No number is blank: # # 1.blank? # => false # 0.blank? # => false def blank? false end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/deep_dup.rb
motion/core_ext/object/deep_dup.rb
class Object # Returns a deep copy of object if it's duplicable. If it's # not duplicable, returns +self+. # # object = Object.new # dup = object.deep_dup # dup.instance_variable_set(:@a, 1) # # object.instance_variable_defined?(:@a) #=> false # dup.instance_variable_defined?(:@a) #=> true def deep_dup duplicable? ? dup : self end end class Array # Returns a deep copy of array. # # array = [1, [2, 3]] # dup = array.deep_dup # dup[1][2] = 4 # # array[1][2] #=> nil # dup[1][2] #=> 4 def deep_dup map { |it| it.deep_dup } end end class Hash # Returns a deep copy of hash. # # hash = { a: { b: 'b' } } # dup = hash.deep_dup # dup[:a][:c] = 'c' # # hash[:a][:c] #=> nil # dup[:a][:c] #=> "c" def deep_dup each_with_object(dup) do |(key, value), hash| hash[key.deep_dup] = value.deep_dup end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/to_query.rb
motion/core_ext/object/to_query.rb
class Object # Converts an object into a string suitable for use as a URL query string, using the given <tt>key</tt> as the # param name. # # Note: This method is defined as a default implementation for all Objects for Hash#to_query to work. def to_query(key) "#{CGI.escape(key.to_param)}=#{CGI.escape(to_param.to_s)}" end end class Array # Converts an array into a string suitable for use as a URL query string, # using the given +key+ as the param name. # # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding" def to_query(key) prefix = "#{key}[]" collect { |value| value.to_query(prefix) }.join '&' end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/try.rb
motion/core_ext/object/try.rb
class Object # Invokes the public method whose name goes as first argument just like # +public_send+ does, except that if the receiver does not respond to it the # call returns +nil+ rather than raising an exception. # # This method is defined to be able to write # # @person.try(:name) # # instead of # # @person ? @person.name : nil # # +try+ returns +nil+ when called on +nil+ regardless of whether it responds # to the method: # # nil.try(:to_i) # => nil, rather than 0 # # Arguments and blocks are forwarded to the method if invoked: # # @posts.try(:each_slice, 2) do |a, b| # ... # end # # The number of arguments in the signature must match. If the object responds # to the method the call is attempted and +ArgumentError+ is still raised # otherwise. # # If +try+ is called without arguments it yields the receiver to a given # block unless it is +nil+: # # @person.try do |p| # ... # end # # Please also note that +try+ is defined on +Object+, therefore it won't work # with instances of classes that do not have +Object+ among their ancestors, # like direct subclasses of +BasicObject+. For example, using +try+ with # +SimpleDelegator+ will delegate +try+ to the target instead of calling it on # delegator itself. def try(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) if respond_to?(a.first) end end # Same as #try, but will raise a NoMethodError exception if the receiving is not nil and # does not implemented the tried method. def try!(*a, &b) if a.empty? && block_given? yield self else public_send(*a, &b) end end end class NilClass # Calling +try+ on +nil+ always returns +nil+. # It becomes specially helpful when navigating through associations that may return +nil+. # # nil.try(:name) # => nil # # Without +try+ # @person && !@person.children.blank? && @person.children.first.name # # With +try+ # @person.try(:children).try(:first).try(:name) def try(*args) nil end def try!(*args) nil end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/acts_like.rb
motion/core_ext/object/acts_like.rb
class Object # A duck-type assistant method. For example, Active Support extends Date # to define an <tt>acts_like_date?</tt> method, and extends Time to define # <tt>acts_like_time?</tt>. As a result, we can do <tt>x.acts_like?(:time)</tt> and # <tt>x.acts_like?(:date)</tt> to do duck-type-safe comparisons, since classes that # we want to act like Time simply need to define an <tt>acts_like_time?</tt> method. def acts_like?(duck) respond_to? :"acts_like_#{duck}?" end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/object/inclusion.rb
motion/core_ext/object/inclusion.rb
class Object # Returns true if this object is included in the argument(s). Argument must be # any object which responds to +#include?+. Usage: # # characters = ['Konata', 'Kagami', 'Tsukasa'] # 'Konata'.in?(characters) # => true # # This will throw an ArgumentError it doesn't respond to +#include?+. def __in_workaround(args) args.include?(self) rescue NoMethodError raise ArgumentError.new("The parameter passed to #in? must respond to #include?") end alias in? __in_workaround end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/date_and_time/calculations.rb
motion/core_ext/date_and_time/calculations.rb
module DateAndTime module Calculations DAYS_INTO_WEEK = { :monday => 0, :tuesday => 1, :wednesday => 2, :thursday => 3, :friday => 4, :saturday => 5, :sunday => 6 } # Returns a new date/time representing yesterday. def yesterday advance(:days => -1) end # Returns a new date/time representing tomorrow. def tomorrow advance(:days => 1) end # Returns true if the date/time is today. def today? to_date == ::Date.current end # Returns true if the date/time is in the past. def past? self < self.class.current end # Returns true if the date/time is in the future. def future? self > self.class.current end # Returns a new date/time the specified number of days ago. def days_ago(days) advance(:days => -days) end # Returns a new date/time the specified number of days in the future. def days_since(days) advance(:days => days) end # Returns a new date/time the specified number of weeks ago. def weeks_ago(weeks) advance(:weeks => -weeks) end # Returns a new date/time the specified number of weeks in the future. def weeks_since(weeks) advance(:weeks => weeks) end # Returns a new date/time the specified number of months ago. def months_ago(months) advance(:months => -months) end # Returns a new date/time the specified number of months in the future. def months_since(months) advance(:months => months) end # Returns a new date/time the specified number of years ago. def years_ago(years) advance(:years => -years) end # Returns a new date/time the specified number of years in the future. def years_since(years) advance(:years => years) end # Returns a new date/time at the start of the month. # DateTime objects will have a time set to 0:00. def beginning_of_month first_hour{ change(:day => 1) } end alias :at_beginning_of_month :beginning_of_month # Returns a new date/time at the start of the quarter. # Example: 1st January, 1st July, 1st October. # DateTime objects will have a time set to 0:00. def beginning_of_quarter first_quarter_month = [10, 7, 4, 1].detect { |m| m <= month } beginning_of_month.change(:month => first_quarter_month) end alias :at_beginning_of_quarter :beginning_of_quarter # Returns a new date/time at the end of the quarter. # Example: 31st March, 30th June, 30th September. # DateTime objects will have a time set to 23:59:59. def end_of_quarter last_quarter_month = [3, 6, 9, 12].detect { |m| m >= month } beginning_of_month.change(:month => last_quarter_month).end_of_month end alias :at_end_of_quarter :end_of_quarter # Return a new date/time at the beginning of the year. # Example: 1st January. # DateTime objects will have a time set to 0:00. def beginning_of_year change(:month => 1).beginning_of_month end alias :at_beginning_of_year :beginning_of_year # Returns a new date/time representing the given day in the next week. # Week is assumed to start on +start_day+, default is # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. # DateTime objects have their time set to 0:00. def next_week(start_day = Date.beginning_of_week) first_hour{ weeks_since(1).beginning_of_week.days_since(days_span(start_day)) } end # Short-hand for months_since(1). def next_month months_since(1) end # Short-hand for months_since(3) def next_quarter months_since(3) end # Short-hand for years_since(1). def next_year years_since(1) end # Returns a new date/time representing the given day in the previous week. # Week is assumed to start on +start_day+, default is # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. # DateTime objects have their time set to 0:00. def prev_week(start_day = Date.beginning_of_week) first_hour{ weeks_ago(1).beginning_of_week.days_since(days_span(start_day)) } end alias_method :last_week, :prev_week # Short-hand for months_ago(1). def prev_month months_ago(1) end alias_method :last_month, :prev_month # Short-hand for months_ago(3). def prev_quarter months_ago(3) end alias_method :last_quarter, :prev_quarter # Short-hand for years_ago(1). def prev_year years_ago(1) end alias_method :last_year, :prev_year # Returns the number of days to the start of the week on the given day. # Week is assumed to start on +start_day+, default is # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. def days_to_week_start(start_day = Date.beginning_of_week) start_day_number = DAYS_INTO_WEEK[start_day] current_day_number = wday != 0 ? wday - 1 : 6 (current_day_number - start_day_number) % 7 end # Returns a new date/time representing the start of this week on the given day. # Week is assumed to start on +start_day+, default is # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. # +DateTime+ objects have their time set to 0:00. def beginning_of_week(start_day = Date.beginning_of_week) result = days_ago(days_to_week_start(start_day)) acts_like?(:time) ? result.midnight : result end alias :at_beginning_of_week :beginning_of_week # Returns Monday of this week assuming that week starts on Monday. # +DateTime+ objects have their time set to 0:00. def monday beginning_of_week(:monday) end # Returns a new date/time representing the end of this week on the given day. # Week is assumed to start on +start_day+, default is # +Date.beginning_of_week+ or +config.beginning_of_week+ when set. # DateTime objects have their time set to 23:59:59. def end_of_week(start_day = Date.beginning_of_week) last_hour{ days_since(6 - days_to_week_start(start_day)) } end alias :at_end_of_week :end_of_week # Returns Sunday of this week assuming that week starts on Monday. # +DateTime+ objects have their time set to 23:59:59. def sunday end_of_week(:monday) end # Returns a new date/time representing the end of the month. # DateTime objects will have a time set to 23:59:59. def end_of_month last_day = ::Time.days_in_month(month, year) last_hour{ days_since(last_day - day) } end alias :at_end_of_month :end_of_month # Returns a new date/time representing the end of the year. # DateTime objects will have a time set to 23:59:59. def end_of_year change(:month => 12).end_of_month end alias :at_end_of_year :end_of_year private def first_hour result = yield acts_like?(:time) ? result.change(:hour => 0) : result end def last_hour result = yield acts_like?(:time) ? result.end_of_day : result end def days_span(day) (DAYS_INTO_WEEK[day] - DAYS_INTO_WEEK[Date.beginning_of_week]) % 7 end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array/conversions.rb
motion/core_ext/array/conversions.rb
class Array # Converts the array to a comma-separated sentence where the last element is # joined by the connector word. # # You can pass the following options to change the default behavior. If you # pass an option key that doesn't exist in the list below, it will raise an # <tt>ArgumentError</tt>. # # Options: # # * <tt>:words_connector</tt> - The sign or word used to join the elements # in arrays with two or more elements (default: ", "). # * <tt>:two_words_connector</tt> - The sign or word used to join the elements # in arrays with two elements (default: " and "). # * <tt>:last_word_connector</tt> - The sign or word used to join the last element # in arrays with three or more elements (default: ", and "). # # [].to_sentence # => "" # ['one'].to_sentence # => "one" # ['one', 'two'].to_sentence # => "one and two" # ['one', 'two', 'three'].to_sentence # => "one, two, and three" # # ['one', 'two'].to_sentence(passing: 'invalid option') # # => ArgumentError: Unknown key :passing # # ['one', 'two'].to_sentence(two_words_connector: '-') # # => "one-two" # # ['one', 'two', 'three'].to_sentence(words_connector: ' or ', last_word_connector: ' or at least ') # # => "one or two or at least three" def to_sentence(options = {}) options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector) default_connectors = { :words_connector => ', ', :two_words_connector => ' and ', :last_word_connector => ', and ' } options = default_connectors.merge!(options) case length when 0 '' when 1 self[0].to_s.dup when 2 "#{self[0]}#{options[:two_words_connector]}#{self[1]}" else "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}" end end # Converts a collection of elements into a formatted string by calling # <tt>to_s</tt> on all elements and joining them. Having this model: # # class Blog < ActiveRecord::Base # def to_s # title # end # end # # Blog.all.map(&:title) #=> ["First Post", "Second Post", "Third post"] # # <tt>to_formatted_s</tt> shows us: # # Blog.all.to_formatted_s # => "First PostSecond PostThird Post" # # Adding in the <tt>:db</tt> argument as the format yields a comma separated # id list: # # Blog.all.to_formatted_s(:db) # => "1,2,3" def to_formatted_s(format = :default) case format when :db if empty? 'null' else collect { |element| element.id }.join(',') end else to_default_s end end alias_method :to_default_s, :to_s alias_method :to_s, :to_formatted_s end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array/extract_options.rb
motion/core_ext/array/extract_options.rb
class Array # Extracts options from a set of arguments. Removes and returns the last # element in the array if it's a hash, otherwise returns a blank hash. def extract_options! if last.is_a?(Hash) pop else {} end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array/grouping.rb
motion/core_ext/array/grouping.rb
class Array # Splits or iterates over the array in groups of size +number+, # padding any remaining slots with +fill_with+ unless it is +false+. # # %w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group} # ["1", "2", "3"] # ["4", "5", "6"] # ["7", "8", "9"] # ["10", nil, nil] # # %w(1 2 3 4 5).in_groups_of(2, '&nbsp;') {|group| p group} # ["1", "2"] # ["3", "4"] # ["5", "&nbsp;"] # # %w(1 2 3 4 5).in_groups_of(2, false) {|group| p group} # ["1", "2"] # ["3", "4"] # ["5"] def in_groups_of(number, fill_with = nil) if fill_with == false collection = self else # size % number gives how many extra we have; # subtracting from number gives how many to add; # modulo number ensures we don't add group of just fill. padding = (number - size % number) % number collection = dup.concat([fill_with] * padding) end if block_given? collection.each_slice(number) { |slice| yield(slice) } else groups = [] collection.each_slice(number) { |group| groups << group } groups end end # Splits or iterates over the array in +number+ of groups, padding any # remaining slots with +fill_with+ unless it is +false+. # # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group} # ["1", "2", "3", "4"] # ["5", "6", "7", nil] # ["8", "9", "10", nil] # # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3, '&nbsp;') {|group| p group} # ["1", "2", "3", "4"] # ["5", "6", "7", "&nbsp;"] # ["8", "9", "10", "&nbsp;"] # # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group} # ["1", "2", "3"] # ["4", "5"] # ["6", "7"] def in_groups(number, fill_with = nil) # size / number gives minor group size; # size % number gives how many objects need extra accommodation; # each group hold either division or division + 1 items. division = size.div number modulo = size % number # create a new array avoiding dup groups = [] start = 0 number.times do |index| length = division + (modulo > 0 && modulo > index ? 1 : 0) groups << last_group = slice(start, length) last_group << fill_with if fill_with != false && modulo > 0 && length == division start += length end if block_given? groups.each { |g| yield(g) } else groups end end # Divides the array into one or more subarrays based on a delimiting +value+ # or the result of an optional block. # # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]] # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]] def split(value = nil, &block) inject([[]]) do |results, element| if block && block.call(element) || value == element results << [] else results.last << element end results end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array/access.rb
motion/core_ext/array/access.rb
class Array # Returns the tail of the array from +position+. # # %w( a b c d ).from(0) # => ["a", "b", "c", "d"] # %w( a b c d ).from(2) # => ["c", "d"] # %w( a b c d ).from(10) # => [] # %w().from(0) # => [] def from(position) self[position, length] || [] end # Returns the beginning of the array up to +position+. # # %w( a b c d ).to(0) # => ["a"] # %w( a b c d ).to(2) # => ["a", "b", "c"] # %w( a b c d ).to(10) # => ["a", "b", "c", "d"] # %w().to(0) # => [] def to(position) first position + 1 end # Equal to <tt>self[1]</tt>. # # %w( a b c d e ).second # => "b" def second self[1] end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array/prepend_and_append.rb
motion/core_ext/array/prepend_and_append.rb
class Array # The human way of thinking about adding stuff to the end of a list is with append alias_method :append, :<< # The human way of thinking about adding stuff to the beginning of a list is with prepend alias_method :prepend, :unshift end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/array/wrap.rb
motion/core_ext/array/wrap.rb
class Array # Wraps its argument in an array unless it is already an array (or array-like). # # Specifically: # # * If the argument is +nil+ an empty list is returned. # * Otherwise, if the argument responds to +to_ary+ it is invoked, and its result returned. # * Otherwise, returns an array with the argument as its single element. # # Array.wrap(nil) # => [] # Array.wrap([1, 2, 3]) # => [1, 2, 3] # Array.wrap(0) # => [0] # # This method is similar in purpose to <tt>Kernel#Array</tt>, but there are some differences: # # * If the argument responds to +to_ary+ the method is invoked. <tt>Kernel#Array</tt> # moves on to try +to_a+ if the returned value is +nil+, but <tt>Array.wrap</tt> returns # such a +nil+ right away. # * If the returned value from +to_ary+ is neither +nil+ nor an +Array+ object, <tt>Kernel#Array</tt> # raises an exception, while <tt>Array.wrap</tt> does not, it just returns the value. # * It does not call +to_a+ on the argument, though special-cases +nil+ to return an empty array. # # The last point is particularly worth comparing for some enumerables: # # Array(foo: :bar) # => [[:foo, :bar]] # Array.wrap(foo: :bar) # => [{:foo=>:bar}] # # There's also a related idiom that uses the splat operator: # # [*object] # # which for +nil+ returns <tt>[]</tt>, and calls to <tt>Array(object)</tt> otherwise. # # Thus, in this case the behavior may be different for +nil+, and the differences with # <tt>Kernel#Array</tt> explained above apply to the rest of <tt>object</tt>s. def self.wrap(object) if object.nil? [] elsif object.respond_to?(:to_ary) object.to_ary || [object] else [object] end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/class/attribute.rb
motion/core_ext/class/attribute.rb
class Class # Declare a class-level attribute whose value is inheritable by subclasses. # Subclasses can change their own value and it will not impact parent class. # # class Base # class_attribute :setting # end # # class Subclass < Base # end # # Base.setting = true # Subclass.setting # => true # Subclass.setting = false # Subclass.setting # => false # Base.setting # => true # # In the above case as long as Subclass does not assign a value to setting # by performing <tt>Subclass.setting = _something_ </tt>, <tt>Subclass.setting</tt> # would read value assigned to parent class. Once Subclass assigns a value then # the value assigned by Subclass would be returned. # # This matches normal Ruby method inheritance: think of writing an attribute # on a subclass as overriding the reader method. However, you need to be aware # when using +class_attribute+ with mutable structures as +Array+ or +Hash+. # In such cases, you don't want to do changes in places but use setters: # # Base.setting = [] # Base.setting # => [] # Subclass.setting # => [] # # # Appending in child changes both parent and child because it is the same object: # Subclass.setting << :foo # Base.setting # => [:foo] # Subclass.setting # => [:foo] # # # Use setters to not propagate changes: # Base.setting = [] # Subclass.setting += [:foo] # Base.setting # => [] # Subclass.setting # => [:foo] # # For convenience, a query method is defined as well: # # Subclass.setting? # => false # # Instances may overwrite the class value in the same way: # # Base.setting = true # object = Base.new # object.setting # => true # object.setting = false # object.setting # => false # Base.setting # => true # # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>. # # object.setting # => NoMethodError # object.setting? # => NoMethodError # # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>. # # object.setting = false # => NoMethodError # # To opt out of both instance methods, pass <tt>instance_accessor: false</tt>. def class_attribute(*attrs) options = attrs.extract_options! # double assignment is used to avoid "assigned but unused variable" warning instance_reader = instance_reader = options.fetch(:instance_accessor, true) && options.fetch(:instance_reader, true) instance_writer = options.fetch(:instance_accessor, true) && options.fetch(:instance_writer, true) attrs.each do |name| define_singleton_method(name) { nil } define_singleton_method("#{name}?") { !!public_send(name) } ivar = "@#{name}" define_singleton_method("#{name}=") do |val| singleton_class.class_eval do remove_possible_method(name) define_method(name) { val } end if singleton_class? class_eval do remove_possible_method(name) define_method(name) do if instance_variable_defined? ivar instance_variable_get ivar else singleton_class.send name end end end end val end if instance_reader remove_possible_method name define_method(name) do if instance_variable_defined?(ivar) instance_variable_get ivar else self.class.public_send name end end define_method("#{name}?") { !!public_send(name) } end attr_writer name if instance_writer end end private def singleton_class? ancestors.first != self end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/class/attribute_accessors.rb
motion/core_ext/class/attribute_accessors.rb
# Extends the class object with class and instance accessors for class attributes, # just like the native attr* accessors for instance attributes. class Class # Defines a class attribute if it's not defined and creates a reader method that # returns the attribute value. # # class Person # cattr_reader :hair_colors # end # # Person.class_variable_set("@@hair_colors", [:brown, :black]) # Person.hair_colors # => [:brown, :black] # Person.new.hair_colors # => [:brown, :black] # # The attribute name must be a valid method name in Ruby. # # class Person # cattr_reader :"1_Badname " # end # # => NameError: invalid attribute name # # If you want to opt out the instance reader method, you can pass <tt>instance_reader: false</tt> # or <tt>instance_accessor: false</tt>. # # class Person # cattr_reader :hair_colors, instance_reader: false # end # # Person.new.hair_colors # => NoMethodError def cattr_reader(*syms) options = syms.extract_options! syms.each do |sym| raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/ class_exec do unless class_variable_defined?("@@#{sym}") class_variable_set("@@#{sym}", nil) end define_singleton_method sym do class_variable_get("@@#{sym}") end end unless options[:instance_reader] == false || options[:instance_accessor] == false class_exec do define_method sym do self.class.class_variable_get("@@#{sym}") end end end end end # Defines a class attribute if it's not defined and creates a writer method to allow # assignment to the attribute. # # class Person # cattr_writer :hair_colors # end # # Person.hair_colors = [:brown, :black] # Person.class_variable_get("@@hair_colors") # => [:brown, :black] # Person.new.hair_colors = [:blonde, :red] # Person.class_variable_get("@@hair_colors") # => [:blonde, :red] # # The attribute name must be a valid method name in Ruby. # # class Person # cattr_writer :"1_Badname " # end # # => NameError: invalid attribute name # # If you want to opt out the instance writer method, pass <tt>instance_writer: false</tt> # or <tt>instance_accessor: false</tt>. # # class Person # cattr_writer :hair_colors, instance_writer: false # end # # Person.new.hair_colors = [:blonde, :red] # => NoMethodError # # Also, you can pass a block to set up the attribute with a default value. # # class Person # cattr_writer :hair_colors do # [:brown, :black, :blonde, :red] # end # end # # Person.class_variable_get("@@hair_colors") # => [:brown, :black, :blonde, :red] def cattr_writer(*syms) options = syms.extract_options! syms.each do |sym| raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/ class_exec do unless class_variable_defined?("@@#{sym}") class_variable_set("@@#{sym}", nil) end define_singleton_method "#{sym}=" do |obj| class_variable_set("@@#{sym}", obj) end end unless options[:instance_writer] == false || options[:instance_accessor] == false class_exec do define_method "#{sym}=" do |obj| self.class.class_variable_set("@@#{sym}", obj) end end end send("#{sym}=", yield) if block_given? end end # Defines both class and instance accessors for class attributes. # # class Person # cattr_accessor :hair_colors # end # # Person.hair_colors = [:brown, :black, :blonde, :red] # Person.hair_colors # => [:brown, :black, :blonde, :red] # Person.new.hair_colors # => [:brown, :black, :blonde, :red] # # If a subclass changes the value then that would also change the value for # parent class. Similarly if parent class changes the value then that would # change the value of subclasses too. # # class Male < Person # end # # Male.hair_colors << :blue # Person.hair_colors # => [:brown, :black, :blonde, :red, :blue] # # To opt out of the instance writer method, pass <tt>instance_writer: false</tt>. # To opt out of the instance reader method, pass <tt>instance_reader: false</tt>. # # class Person # cattr_accessor :hair_colors, instance_writer: false, instance_reader: false # end # # Person.new.hair_colors = [:brown] # => NoMethodError # Person.new.hair_colors # => NoMethodError # # Or pass <tt>instance_accessor: false</tt>, to opt out both instance methods. # # class Person # cattr_accessor :hair_colors, instance_accessor: false # end # # Person.new.hair_colors = [:brown] # => NoMethodError # Person.new.hair_colors # => NoMethodError # # Also you can pass a block to set up the attribute with a default value. # # class Person # cattr_accessor :hair_colors do # [:brown, :black, :blonde, :red] # end # end # # Person.class_variable_get("@@hair_colors") #=> [:brown, :black, :blonde, :red] def cattr_accessor(*syms, &blk) cattr_reader(*syms) cattr_writer(*syms, &blk) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/anonymous.rb
motion/core_ext/module/anonymous.rb
class Module # A module may or may not have a name. # # module M; end # M.name # => "M" # # m = Module.new # m.name # => nil # # A module gets a name when it is first assigned to a constant. Either # via the +module+ or +class+ keyword or by an explicit assignment: # # m = Module.new # creates an anonymous module # M = m # => m gets a name here as a side-effect # m.name # => "M" def anonymous? name.nil? end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/remove_method.rb
motion/core_ext/module/remove_method.rb
class Module def remove_possible_method(method) if method_defined?(method) || private_method_defined?(method) undef_method(method) end end def redefine_method(method, &block) remove_possible_method(method) define_method(method, &block) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/reachable.rb
motion/core_ext/module/reachable.rb
class Module def reachable? #:nodoc: !anonymous? && name.safe_constantize.equal?(self) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/attribute_accessors.rb
motion/core_ext/module/attribute_accessors.rb
class Module def mattr_reader(*syms) receiver = self options = syms.extract_options! syms.each do |sym| raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/ class_exec do unless class_variable_defined?("@@#{sym}") class_variable_set("@@#{sym}", nil) end define_singleton_method sym do class_variable_get("@@#{sym}") end end unless options[:instance_reader] == false || options[:instance_accessor] == false class_exec do define_method sym do receiver.class_variable_get("@@#{sym}") end end end end end def mattr_writer(*syms) receiver = self options = syms.extract_options! syms.each do |sym| raise NameError.new('invalid attribute name') unless sym =~ /^[_A-Za-z]\w*$/ class_exec do define_singleton_method "#{sym}=" do |obj| class_variable_set("@@#{sym}", obj) end end unless options[:instance_writer] == false || options[:instance_accessor] == false class_exec do define_method "#{sym}=" do |obj| receiver.class_variable_set("@@#{sym}", obj) end end end end end # Extends the module object with module and instance accessors for class attributes, # just like the native attr* accessors for instance attributes. # # module AppConfiguration # mattr_accessor :google_api_key # # self.google_api_key = "123456789" # end # # AppConfiguration.google_api_key # => "123456789" # AppConfiguration.google_api_key = "overriding the api key!" # AppConfiguration.google_api_key # => "overriding the api key!" def mattr_accessor(*syms) mattr_reader(*syms) mattr_writer(*syms) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/introspection.rb
motion/core_ext/module/introspection.rb
class Module # Returns the name of the module containing this one. # # M::N.parent_name # => "M" def parent_name if defined? @parent_name @parent_name else @parent_name = name =~ /::[^:]+\Z/ ? $`.freeze : nil end end # Returns the module which contains this one according to its name. # # module M # module N # end # end # X = M::N # # M::N.parent # => M # X.parent # => M # # The parent of top-level and anonymous modules is Object. # # M.parent # => Object # Module.new.parent # => Object def parent parent_name ? parent_name.constantize : Object end # Returns all the parents of this module according to its name, ordered from # nested outwards. The receiver is not contained within the result. # # module M # module N # end # end # X = M::N # # M.parents # => [Object] # M::N.parents # => [M, Object] # X.parents # => [M, Object] def parents parents = [] if parent_name parts = parent_name.split('::') until parts.empty? parents << (parts * '::').constantize parts.pop end end parents << Object unless parents.include? Object parents end def local_constants #:nodoc: constants(false) end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/delegation.rb
motion/core_ext/module/delegation.rb
class Module # Provides a delegate class method to easily expose contained objects' public methods # as your own. Pass one or more methods (specified as symbols or strings) # and the name of the target object via the <tt>:to</tt> option (also a symbol # or string). At least one method and the <tt>:to</tt> option are required. # # Delegation is particularly useful with Active Record associations: # # class Greeter < ActiveRecord::Base # def hello # 'hello' # end # # def goodbye # 'goodbye' # end # end # # class Foo < ActiveRecord::Base # belongs_to :greeter # delegate :hello, to: :greeter # end # # Foo.new.hello # => "hello" # Foo.new.goodbye # => NoMethodError: undefined method `goodbye' for #<Foo:0x1af30c> # # Multiple delegates to the same target are allowed: # # class Foo < ActiveRecord::Base # belongs_to :greeter # delegate :hello, :goodbye, to: :greeter # end # # Foo.new.goodbye # => "goodbye" # # Methods can be delegated to instance variables, class variables, or constants # by providing them as a symbols: # # class Foo # CONSTANT_ARRAY = [0,1,2,3] # @@class_array = [4,5,6,7] # # def initialize # @instance_array = [8,9,10,11] # end # delegate :sum, to: :CONSTANT_ARRAY # delegate :min, to: :@@class_array # delegate :max, to: :@instance_array # end # # Foo.new.sum # => 6 # Foo.new.min # => 4 # Foo.new.max # => 11 # # It's also possible to delegate a method to the class by using +:class+: # # class Foo # def self.hello # "world" # end # # delegate :hello, to: :class # end # # Foo.new.hello # => "world" # # Delegates can optionally be prefixed using the <tt>:prefix</tt> option. If the value # is <tt>true</tt>, the delegate methods are prefixed with the name of the object being # delegated to. # # Person = Struct.new(:name, :address) # # class Invoice < Struct.new(:client) # delegate :name, :address, to: :client, prefix: true # end # # john_doe = Person.new('John Doe', 'Vimmersvej 13') # invoice = Invoice.new(john_doe) # invoice.client_name # => "John Doe" # invoice.client_address # => "Vimmersvej 13" # # It is also possible to supply a custom prefix. # # class Invoice < Struct.new(:client) # delegate :name, :address, to: :client, prefix: :customer # end # # invoice = Invoice.new(john_doe) # invoice.customer_name # => 'John Doe' # invoice.customer_address # => 'Vimmersvej 13' # # If the delegate object is +nil+ an exception is raised, and that happens # no matter whether +nil+ responds to the delegated method. You can get a # +nil+ instead with the +:allow_nil+ option. # # class Foo # attr_accessor :bar # def initialize(bar = nil) # @bar = bar # end # delegate :zoo, to: :bar # end # # Foo.new.zoo # raises NoMethodError exception (you called nil.zoo) # # class Foo # attr_accessor :bar # def initialize(bar = nil) # @bar = bar # end # delegate :zoo, to: :bar, allow_nil: true # end # # Foo.new.zoo # returns nil def delegate(*methods) options = methods.pop unless options.is_a?(Hash) && to = options[:to] raise ArgumentError, 'Delegation needs a target. Supply an options hash with a :to key as the last argument (e.g. delegate :hello, to: :greeter).' end prefix, allow_nil = options.values_at(:prefix, :allow_nil) unguarded = !allow_nil if prefix == true && to =~ /^[^a-z_]/ raise ArgumentError, 'Can only automatically set the delegation prefix when delegating to a method.' end method_prefix = \ if prefix "#{prefix == true ? to : prefix}_" else '' end reference, *hierarchy = to.to_s.split('.') entry = resolver = case reference when 'self' ->(_self) { _self } when /^@@/ ->(_self) { _self.class.class_variable_get(reference) } when /^@/ ->(_self) { _self.instance_variable_get(reference) } when /^[A-Z]/ ->(_self) { if reference.to_s =~ /::/ then reference.constantize else _self.class.const_get(reference) end } else ->(_self) { _self.send(reference) } end resolver = ->(_self) { hierarchy.reduce(entry.call(_self)) { |obj, method| obj.public_send(method) } } unless hierarchy.empty? methods.each do |method| module_exec do # def customer_name(*args, &block) # begin # if unguarded || client || client.respond_to?(:name) # client.name(*args, &block) # end # rescue client.nil? && NoMethodError # raise "..." # end # end define_method("#{method_prefix}#{method}") do |*args, &block| target = resolver.call(self) if unguarded || target || target.respond_to?(method) begin target.public_send(method, *args, &block) rescue target.nil? && NoMethodError # only rescue NoMethodError when target is nil raise "#{self}##{method_prefix}#{method} delegated to #{to}.#{method}, but #{to} is nil: #{self.inspect}" end end end end end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/aliasing.rb
motion/core_ext/module/aliasing.rb
class Module # Encapsulates the common pattern of: # # alias_method :foo_without_feature, :foo # alias_method :foo, :foo_with_feature # # With this, you simply do: # # alias_method_chain :foo, :feature # # And both aliases are set up for you. # # Query and bang methods (foo?, foo!) keep the same punctuation: # # alias_method_chain :foo?, :feature # # is equivalent to # # alias_method :foo_without_feature?, :foo? # alias_method :foo?, :foo_with_feature? # # so you can safely chain foo, foo?, and foo! with the same feature. def alias_method_chain(target, feature) # Strip out punctuation on predicates or bang methods since # e.g. target?_without_feature is not a valid method name. aliased_target, punctuation = target.to_s.sub(/([?!=])$/, ''), $1 yield(aliased_target, punctuation) if block_given? with_method = "#{aliased_target}_with_#{feature}#{punctuation}" without_method = "#{aliased_target}_without_#{feature}#{punctuation}" alias_method without_method, target alias_method target, with_method case when public_method_defined?(without_method) public target when protected_method_defined?(without_method) protected target when private_method_defined?(without_method) private target end end # Allows you to make aliases for attributes, which includes # getter, setter, and query methods. # # class Content < ActiveRecord::Base # # has a title attribute # end # # class Email < Content # alias_attribute :subject, :title # end # # e = Email.find(1) # e.title # => "Superstars" # e.subject # => "Superstars" # e.subject? # => true # e.subject = "Megastars" # e.title # => "Megastars" def alias_attribute(new_name, old_name) module_exec do define_method(new_name) { self.send(old_name) } # def subject; self.title; end define_method("#{new_name}?") { self.send("#{old_name}?") } # def subject?; self.title?; end define_method("#{new_name}=") { |v| self.send("#{old_name}=", v) } # def subject=(v); self.title = v; end end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/module/attr_internal.rb
motion/core_ext/module/attr_internal.rb
class Module # Declares an attribute reader backed by an internally-named instance variable. def attr_internal_reader(*attrs) attrs.each {|attr_name| attr_internal_define(attr_name, :reader)} end # Declares an attribute writer backed by an internally-named instance variable. def attr_internal_writer(*attrs) attrs.each {|attr_name| attr_internal_define(attr_name, :writer)} end # Declares an attribute reader and writer backed by an internally-named instance # variable. def attr_internal_accessor(*attrs) attr_internal_reader(*attrs) attr_internal_writer(*attrs) end alias_method :attr_internal, :attr_internal_accessor class << self; attr_accessor :attr_internal_naming_format end self.attr_internal_naming_format = '@_%s' private def attr_internal_ivar_name(attr) Module.attr_internal_naming_format % attr end def attr_internal_define(attr_name, type) internal_name = attr_internal_ivar_name(attr_name).sub(/\A@/, '') class_eval do # class_eval is necessary on 1.9 or else the methods a made private # use native attr_* methods as they are faster on some Ruby implementations send("attr_#{type}", internal_name) end attr_name, internal_name = "#{attr_name}=", "#{internal_name}=" if type == :writer alias_method attr_name, internal_name remove_method internal_name end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/numeric/time.rb
motion/core_ext/numeric/time.rb
class Numeric # Enables the use of time calculations and declarations, like 45.minutes + 2.hours + 4.years. # # These methods use Time#advance for precise date calculations when using from_now, ago, etc. # as well as adding or subtracting their results from a Time object. For example: # # # equivalent to Time.now.advance(months: 1) # 1.month.from_now # # # equivalent to Time.now.advance(years: 2) # 2.years.from_now # # # equivalent to Time.now.advance(months: 4, years: 5) # (4.months + 5.years).from_now # # While these methods provide precise calculation when used as in the examples above, care # should be taken to note that this is not true if the result of `months', `years', etc is # converted before use: # # # equivalent to 30.days.to_i.from_now # 1.month.to_i.from_now # # # equivalent to 365.25.days.to_f.from_now # 1.year.to_f.from_now # # In such cases, Ruby's core # Date[http://ruby-doc.org/stdlib/libdoc/date/rdoc/Date.html] and # Time[http://ruby-doc.org/stdlib/libdoc/time/rdoc/Time.html] should be used for precision # date and time arithmetic. def seconds MotionSupport::Duration.new(self, [[:seconds, self]]) end alias :second :seconds def minutes MotionSupport::Duration.new(self * 60, [[:seconds, self * 60]]) end alias :minute :minutes def hours MotionSupport::Duration.new(self * 3600, [[:seconds, self * 3600]]) end alias :hour :hours def days MotionSupport::Duration.new(self * 24.hours, [[:days, self]]) end alias :day :days def weeks MotionSupport::Duration.new(self * 7.days, [[:days, self * 7]]) end alias :week :weeks def fortnights MotionSupport::Duration.new(self * 2.weeks, [[:days, self * 14]]) end alias :fortnight :fortnights # Reads best without arguments: 10.minutes.ago def ago(time = ::Time.now) time - self end # Reads best with argument: 10.minutes.until(time) alias :until :ago # Reads best with argument: 10.minutes.since(time) def since(time = ::Time.now) time + self end # Reads best without arguments: 10.minutes.from_now alias :from_now :since end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/numeric/conversions.rb
motion/core_ext/numeric/conversions.rb
class Numeric # Provides options for converting numbers into formatted strings. # Right now, options are only provided for phone numbers. # # ==== Options # # For details on which formats use which options, see MotionSupport::NumberHelper # # ==== Examples # # Phone Numbers: # 5551234.to_s(:phone) # => 555-1234 # 1235551234.to_s(:phone) # => 123-555-1234 # 1235551234.to_s(:phone, area_code: true) # => (123) 555-1234 # 1235551234.to_s(:phone, delimiter: ' ') # => 123 555 1234 # 1235551234.to_s(:phone, area_code: true, extension: 555) # => (123) 555-1234 x 555 # 1235551234.to_s(:phone, country_code: 1) # => +1-123-555-1234 # 1235551234.to_s(:phone, country_code: 1, extension: 1343, delimiter: '.') # # => +1.123.555.1234 x 1343 def to_formatted_s(format = :default, options = {}) case format when :phone return MotionSupport::NumberHelper.number_to_phone(self, options) else self.to_default_s end end [Float, Fixnum, Bignum].each do |klass| klass.send(:alias_method, :to_default_s, :to_s) klass.send(:define_method, :to_s) do |*args| if args[0].is_a?(Symbol) format = args[0] options = args[1] || {} self.to_formatted_s(format, options) else to_default_s(*args) end end end end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
rubymotion-community/motion-support
https://github.com/rubymotion-community/motion-support/blob/f9e04234315327a64db8181e3af2c7b87ba3e13a/motion/core_ext/numeric/bytes.rb
motion/core_ext/numeric/bytes.rb
class Numeric KILOBYTE = 1024 MEGABYTE = KILOBYTE * 1024 GIGABYTE = MEGABYTE * 1024 TERABYTE = GIGABYTE * 1024 PETABYTE = TERABYTE * 1024 EXABYTE = PETABYTE * 1024 # Enables the use of byte calculations and declarations, like 45.bytes + 2.6.megabytes def bytes self end alias :byte :bytes def kilobytes self * KILOBYTE end alias :kilobyte :kilobytes def megabytes self * MEGABYTE end alias :megabyte :megabytes def gigabytes self * GIGABYTE end alias :gigabyte :gigabytes def terabytes self * TERABYTE end alias :terabyte :terabytes def petabytes self * PETABYTE end alias :petabyte :petabytes def exabytes self * EXABYTE end alias :exabyte :exabytes end
ruby
MIT
f9e04234315327a64db8181e3af2c7b87ba3e13a
2026-01-04T17:47:41.763315Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/trigger.rb
spec/trigger.rb
require 'spec_helper' describe 'trigger' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) @application = gen_name 'application' @applicationid = zbx.applications.create( name: @application, hostid: @templateid ) @item = gen_name 'item' @proc = "proc.num[#{gen_name 'proc'}]" @itemid = zbx.items.create( name: @item, key_: @proc, status: 0, hostid: @templateid, applications: [@applicationid] ) end context 'when name not exists' do describe 'create' do it 'should return integer id' do @trigger = gen_name 'trigger' triggerid = zbx.triggers.create( description: @trigger, expression: "{#{@template}:#{@proc}.last(0)}<1", comments: 'Bla-bla is faulty (disaster)', priority: 5, status: 0, type: 0, tags: [ { tag: 'proc', value: @proc.to_s }, { tag: 'error', value: '' } ] ) expect(triggerid).to be_kind_of(Integer) end end end context 'when name exists' do before :all do @trigger = gen_name 'trigger' @triggerid = zbx.triggers.create( description: @trigger, expression: "{#{@template}:#{@proc}.last(0)}<1", comments: 'Bla-bla is faulty (disaster)', priority: 5, status: 0, type: 0, tags: [ { tag: 'proc', value: @proc.to_s }, { tag: 'error', value: '' } ] ) end describe 'get_id' do it 'should return id' do expect(zbx.triggers.get_id(description: @trigger)).to eq @triggerid end end describe 'create_or_update' do it 'should return id of updated trigger' do expect( zbx.triggers.create_or_update( description: @trigger, hostid: @templateid ) ).to eq @triggerid end end describe 'delete' do it 'should return id' do expect(zbx.triggers.delete(@triggerid)).to eq @triggerid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/usergroup.rb
spec/usergroup.rb
require 'spec_helper' describe 'usergroup' do context 'when not exists' do it 'should be integer id' do usergroupid = zbx.usergroups.create(name: gen_name('usergroup')) expect(usergroupid).to be_kind_of(Integer) end end context 'when exists' do before do @usergroup = gen_name 'usergroup' @usergroupid = zbx.usergroups.create(name: @usergroup) @user = gen_name 'user' @roleid = "1" @userid = zbx.users.create( alias: @user, name: @user, surname: @user, passwd: @user, usrgrps: [{usrgrpid: @usergroupid}], roleid: @roleid ) @usergroup2 = gen_name 'usergroup' @usergroupid2 = zbx.usergroups.create(name: @usergroup2) @user2 = gen_name 'user' @userid2 = zbx.users.create( alias: @user2, name: @user2, surname: @user2, passwd: @user2, usrgrps: [{usrgrpid: @usergroupid2}], roleid: @roleid ) end describe 'get_or_create' do it 'should return id' do expect(zbx.usergroups.get_or_create(name: @usergroup)).to eq @usergroupid end end describe 'add_user' do it 'should return id' do expect( zbx.usergroups.add_user( usrgrpids: [@usergroupid], userids: [@userid,@userid2] ) ).to eq @usergroupid end end describe 'update_users' do it 'should return id' do expect( zbx.usergroups.update_users( usrgrpids: [@usergroupid2], userids: [@userid2] ) ).to eq @usergroupid2 end end describe 'set_permissions' do it 'should return id' do expect( zbx.usergroups.permissions( usrgrpid: @usergroupid, hostgroupids: zbx.hostgroups.all.values, permission: 3 ) ).to eq @usergroupid end end describe 'delete' do it 'should raise error when has users with only one group' do expect { zbx.usergroups.delete(@usergroupid) }.to raise_error(ZabbixApi::ApiError) end it 'should return id of deleted group' do usergroupid = zbx.usergroups.create(name: gen_name('usergroup')) expect(zbx.usergroups.delete(usergroupid)).to eq usergroupid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/httptest.rb
spec/httptest.rb
require 'spec_helper' describe 'httptest' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) end context 'when name not exists' do before do @httptest_name = gen_name 'httptest_name' @step_name = gen_name 'step_name' end describe 'create' do it 'should return integer id' do httptestid = zbx.httptests.create( name: @httptest_name, hostid: @templateid, steps: [ { name: @step_name, url: 'http://localhost/zabbix/', status_codes: '200', no: 1 } ] ) expect(httptestid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.httptests.get_id(name: @httptest_name)).to be_kind_of(NilClass) expect(zbx.httptests.get_id('name' => @httptest_name)).to be_kind_of(NilClass) end end end context 'when name exists' do before :all do @httptest_name = gen_name 'httptest_name' @step_name = gen_name 'step_name' @httptestid = zbx.httptests.create( name: @httptest_name, hostid: @templateid, steps: [ { name: @step_name, url: 'http://localhost/zabbix/', status_codes: '200', no: 1 } ] ) end describe 'get_or_create' do it 'should return id of httptest' do expect( zbx.httptests.get_or_create( name: @httptest_name, hostid: @templateid, steps: [ { name: @step_name, url: 'http://localhost/zabbix/', status_codes: '200', no: 1 } ] ) ).to eq @httptestid end end describe 'get_full_data' do it 'should contain created httptest' do expect(zbx.httptests.get_full_data(name: @httptest_name)[0]).to include('name' => @httptest_name) end end describe 'get_id' do it 'should return id of httptest' do expect(zbx.httptests.get_id(name: @httptest_name)).to eq @httptestid expect(zbx.httptests.get_id('name' => @httptest_name)).to eq @httptestid end end describe 'create_or_update' do it 'should return id of updated httptest' do expect( zbx.httptests.create_or_update( name: @httptest_name, hostid: @templateid, steps: [ { name: @step_name, url: 'http://localhost/zabbix/', status_codes: '200', no: 1 } ] ) ).to eq @httptestid end end describe 'update' do it 'should return id' do expect( zbx.httptests.update( httptestid: @httptestid, status: 0, steps: [ { name: @step_name, url: 'http://localhost/zabbix/', status_codes: '200', no: 1 } ] ) ).to eq @httptestid end end describe 'delete' do it 'HTTPTEST: Delete' do expect(zbx.httptests.delete(@httptestid)).to eq @httptestid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/basic_func.rb
spec/basic_func.rb
require 'spec_helper' describe ZabbixApi::Basic do end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/script.rb
spec/script.rb
require 'spec_helper' describe 'script' do before :all do @hostid = zbx.hosts.get_id(host: 'Zabbix server') end context 'when name not exists' do before do @script = gen_name 'script' end describe 'create' do it 'should return integer id' do scriptid = zbx.scripts.create( name: @script, command: 'hostname' ) expect(scriptid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.scripts.get_id(name: @script)).to be_kind_of(NilClass) end end end context 'when name exists' do before :all do @script = gen_name 'script' @scriptid = zbx.scripts.create( name: @script, command: 'hostname' ) end describe 'get_or_create' do it 'should return id of script' do expect(zbx.scripts.get_or_create( name: @script, command: 'hostname' )).to eq @scriptid end end describe 'get_full_data' do it 'should contains created script' do expect(zbx.scripts.get_full_data(name: @script)[0]).to include('name' => @script) end end describe 'get_id' do it 'should return id of script' do expect(zbx.scripts.get_id(name: @script)).to eq @scriptid end end it 'should raise error on no identity given' do expect { zbx.scripts.get_id({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update' do it 'should return id' do expect(zbx.scripts.update( scriptid: zbx.scripts.get_id(name: @script), # enable_confirmation: 1, confirmation: 'Are you sure you would like to show the system hostname?' )).to eq @scriptid end end describe 'create_or_update' do it 'should update existing script' do expect(zbx.scripts.get_or_create( name: @script, command: 'hostname' )).to eq @scriptid end it 'should create script' do new_script_id = zbx.scripts.get_or_create( name: @script + '____1', command: 'hostname' ) expect(new_script_id).to be_kind_of(Integer) expect(new_script_id).to be > @scriptid end end # TODO: see if we can get this test working with travis ci (passes on standalone zabbix server) # describe 'execute' do # it "should return success response" do # expect(zbx.scripts.execute(:scriptid => @scriptid, :hostid => @hostid)).to include("response" => "success") # end # end describe 'getscriptsbyhost' do it 'should return object with hostid and script' do expect(zbx.scripts.getscriptsbyhost([@hostid])[@hostid.to_s].select { |script| script[:name] == @script }).to_not be_nil end end describe 'delete' do before :all do @result = zbx.scripts.delete(@scriptid) end it 'should return deleted id' do expect(@result).to eq @scriptid end it 'should delete script from zabbix' do expect(zbx.scripts.get_id(name: @script)).to be_nil end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/maintenance.rb
spec/maintenance.rb
require 'spec_helper' describe 'maintenance' do context 'when not exists' do before :all do @hostgroupid = zbx.hostgroups.create(name: "hostgroup_#{rand(1_000_000)}") end describe 'create' do it 'should return integer id after creation' do maintenanceid = zbx.maintenance.create( name: "maintenance_#{rand(1_000_000)}", groupids: [@hostgroupid], active_since: '1358844540', active_till: '1390466940', timeperiods: [timeperiod_type: 3, every: 1, dayofweek: 64, start_time: 64_800, period: 3_600] ) expect(maintenanceid).to be_kind_of(Integer) zbx.maintenance.delete(maintenanceid) end end after :all do zbx.hostgroups.delete(@hostgroupid) end end context 'when exists' do before :all do @hostgroupid_when_exists = zbx.hostgroups.create(name: "hostgroup_#{rand(1_000_000)}") @maintenance = gen_name('maintenance') @maintenanceid = zbx.maintenance.create( name: @maintenance, groupids: [@hostgroupid_when_exists], active_since: '1358844540', active_till: '1390466940', timeperiods: [timeperiod_type: 3, every: 1, dayofweek: 64, start_time: 64_800, period: 3_600] ) end describe 'get_id' do it 'should return id' do expect(zbx.maintenance.get_id(name: @maintenance)).to eq @maintenanceid end it 'should return nil for not existing group' do expect(zbx.maintenance.get_id(name: "#{@maintenance}______")).to be_kind_of(NilClass) end end describe 'get_or_create' do it 'should return id of existing maintenance' do expect(zbx.maintenance.get_or_create(name: @maintenance)).to eq @maintenanceid end end describe 'create_or_update' do it 'should return id of maintenance' do expect(zbx.maintenance.create_or_update(name: @maintenance)).to eq @maintenanceid end end describe 'all' do it 'should contains created maintenance' do expect(zbx.maintenance.all).to include(@maintenance => @maintenanceid.to_s) end end describe 'delete' do it 'shold return id' do expect(zbx.maintenance.delete(@maintenanceid)).to eq @maintenanceid end end after :all do zbx.hostgroups.delete(@hostgroupid_when_exists) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/event.rb
spec/event.rb
require 'spec_helper' describe 'event' do before do @eventname = gen_name 'event' @usergroupid = zbx.usergroups.create(name: gen_name('usergroup')) @eventdata = { name: @eventname, eventsource: '0', # event source is a triggerid status: '0', # event is enabled esc_period: '120', # how long each step should take def_shortdata: 'Email header', def_longdata: 'Email content', maintenance_mode: '1', filter: { evaltype: '1', # perform 'and' between the conditions conditions: [ { conditiontype: '3', # trigger name operator: '2', # like value: 'pattern' # the pattern }, { conditiontype: '4', # trigger severity operator: '5', # >= value: '3' # average } ] }, operations: [ { operationtype: '0', # send message opmessage_grp: [ # who the message will be sent to { usrgrpid: @usergroupid } ], opmessage: { default_msg: '0', # use default message mediatypeid: '1' # email id } } ], recovery_operations: [ { operationtype: '11', # send recovery message opmessage_grp: [ # who the message will be sent to { usrgrpid: @usergroupid } ], opmessage: { default_msg: '0', # use default message mediatypeid: '1' # email id } } ] } end context 'when incorrect method' do describe 'create' do it 'should raise ApiError' do expect{zbx.events.create(@eventdata)}. to raise_error(ZabbixApi::ApiError, /.*\"data\": \"Incorrect method \\\"event.create\\\"\.\"/) end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/application.rb
spec/application.rb
require 'spec_helper' describe 'application' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) end context 'when name not exists' do before do @application = gen_name 'application' end describe 'create' do it 'should return integer id' do applicationid = zbx.applications.create( name: @application, hostid: @templateid ) expect(applicationid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.applications.get_id(name: @application)).to be_kind_of(NilClass) end end end context 'when name exists' do before :all do @application = gen_name 'application' @applicationid = zbx.applications.create( name: @application, hostid: @templateid ) end describe 'get_or_create' do it 'should return id of application' do expect( zbx.applications.get_or_create( name: @application, hostid: @templateid ) ).to eq @applicationid end end describe 'get_full_data' do it 'should contains created application' do expect(zbx.applications.get_full_data(name: @application)[0]).to include('name' => @application) end end describe 'get_id' do it 'should return id of application' do expect(zbx.applications.get_id(name: @application)).to eq @applicationid end end describe 'create_or_update' do it 'should return id of updated application' do expect( zbx.applications.create_or_update( name: @application, hostid: @templateid ) ).to eq @applicationid end end describe 'delete' do it 'should return id' do expect(zbx.applications.delete(@applicationid)).to eq @applicationid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/graph.rb
spec/graph.rb
require 'spec_helper' describe 'graph' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) @application = gen_name 'application' @applicationid = zbx.applications.create( name: @application, hostid: @templateid ) @item = gen_name 'item' @itemid = zbx.items.create( name: @item, key_: "proc.num[#{gen_name 'proc'}]", status: 0, hostid: @templateid, applications: [@applicationid] ) @color = '123456' end def gitems { itemid: @itemid, calc_fnc: '3', color: @color, type: '0', periods_cnt: '5' } end def create_graph(graph, _itemid) zbx.graphs.create( gitems: [gitems], show_triggers: '0', name: graph, width: '900', height: '200' ) end context 'when name not exists' do describe 'create' do it 'should return integer id' do @graph = gen_name 'graph' expect(create_graph(@graph, @itemid)).to be_kind_of(Integer) end end end context 'when name exists' do before :all do @graph = gen_name 'graph' @graphid = create_graph(@graph, @itemid) end describe 'get_or_create' do it 'should return id of existing graph' do expect( zbx.graphs.get_or_create( gitems: [gitems], show_triggers: '0', name: @graph, width: '900', height: '200' ) ).to eq @graphid end end describe 'get_items' do it 'should return array' do expect(zbx.graphs.get_items(@graphid)).to be_kind_of(Array) end it 'should return array of size 1' do expect(zbx.graphs.get_items(@graphid).size).to eq 1 end it 'should include correct item' do expect(zbx.graphs.get_items(@graphid)[0]).to include('color' => @color) end end describe 'get_id' do it 'should return id' do expect(zbx.graphs.get_id(name: @graph)).to eq @graphid end end describe 'get_ids_by_host' do it 'should contains id of graph' do graph_array = zbx.graphs.get_ids_by_host(host: @host) expect(graph_array).to be_kind_of(Array) expect(graph_array).to include(@graphid.to_s) end end describe 'update' do it 'should return id' do expect( zbx.graphs.update( graphid: @graphid, gitems: [gitems], ymax_type: 1 ) ).to eq @graphid end end describe 'create_or_update' do it 'should return existing id' do expect( zbx.graphs.create_or_update( gitems: [gitems], show_triggers: '1', name: @graph, width: '900', height: '200' ) ).to eq @graphid end end describe 'delete' do it 'should return true' do expect(zbx.graphs.delete(@graphid)).to eq @graphid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/item.rb
spec/item.rb
require 'spec_helper' describe 'item' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) @application = gen_name 'application' @applicationid = zbx.applications.create( name: @application, hostid: @templateid ) end context 'when name not exists' do before do @item = gen_name 'item' end describe 'create' do it 'should return integer id' do itemid = zbx.items.create( name: @item, key_: "proc.num[#{gen_name 'proc'}]", status: 0, hostid: @templateid, applications: [@applicationid] ) expect(itemid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.items.get_id(name: @item)).to be_kind_of(NilClass) end end end context 'when name exists' do before :all do @item = gen_name 'item' @itemid = zbx.items.create( name: @item, key_: 'proc.num[aaa]', status: 0, hostid: @templateid, applications: [@applicationid] ) end describe 'get_or_create' do it 'should return id of item' do expect( zbx.items.get_or_create( name: @item, key_: "proc.num[#{gen_name 'proc'}]", status: 0, hostid: @templateid, applications: [@applicationid] ) ).to eq @itemid end end describe 'get_full_data' do it 'should contains created item' do expect(zbx.items.get_full_data(name: @item)[0]).to include('name' => @item) end end describe 'get_id' do it 'should return id of item' do expect(zbx.items.get_id(name: @item)).to eq @itemid end end it 'should raise error on no identity given' do expect { zbx.items.get_id({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update' do it 'should return id' do expect( zbx.items.update( itemid: zbx.items.get_id(name: @item), status: 1 ) ).to eq @itemid end end describe 'create_or_update' do it 'should update existing item' do expect( zbx.items.create_or_update( name: @item, key_: "proc.num[#{gen_name 'proc'}]", status: 0, hostid: @templateid, applications: [@applicationid] ) ).to eq @itemid end it 'should create item' do new_item_id = zbx.items.create_or_update( name: @item + '____1', key_: "proc.num[#{gen_name 'proc'}]", status: 0, hostid: @templateid, applications: [@applicationid] ) expect(new_item_id).to be_kind_of(Integer) expect(new_item_id).to be > @itemid end end describe 'delete' do before :all do @result = zbx.items.delete(@itemid) end it 'should return deleted id' do expect(@result).to eq @itemid end it 'should delete item from zabbix' do expect(zbx.items.get_id(name: @item)).to be_nil end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/host.rb
spec/host.rb
require 'spec_helper' describe 'host' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) end context 'when name not exists' do before do @host = gen_name 'host' end describe 'create' do it 'should return integer id' do hostid = zbx.hosts.create( host: @host, interfaces: [ { type: 1, main: 1, ip: '10.20.48.88', dns: '', port: '10050', useip: 1 } ], groups: [groupid: @hostgroupid] ) expect(hostid).to be_kind_of(Integer) end it 'should create host in multiple groups' do @hostgroupid2 = zbx.hostgroups.create(name: gen_name('hostgroup')) host = gen_name('host') hostid = zbx.hosts.create( host: host, interfaces: [ { type: 1, main: 1, ip: '192.168.0.1', dns: 'server.example.org', port: '10050', useip: 0 } ], groups: [ { groupid: @hostgroupid }, { groupid: @hostgroupid2 } ] ) expect(hostid).to be_kind_of Integer host = zbx.query(method: 'host.get', params: { hostids: [hostid], selectGroups: 'extend' }).first expect(host['hostid'].to_i).to eq hostid expect(host['groups'].size).to eq 2 end end describe 'get_id' do it 'should return nil' do expect(zbx.hosts.get_id(host: @host)).to be_kind_of(NilClass) expect(zbx.hosts.get_id('host' => @host)).to be_kind_of(NilClass) end end end context 'when name exists' do before :all do @host = gen_name 'host' @hostid = zbx.hosts.create( host: @host, interfaces: [ { type: 1, main: 1, ip: '10.20.48.88', dns: '', port: '10050', useip: 1 } ], groups: [groupid: @hostgroupid] ) end describe 'get_or_create' do it 'should return id of host' do expect( zbx.hosts.get_or_create( host: @host, groups: [groupid: @hostgroupid] ) ).to eq @hostid end end describe 'get_full_data' do it 'should contains created host' do expect(zbx.hosts.get_full_data(host: @host)[0]).to include('host' => @host) end end describe 'get_id' do it 'should return id of host' do expect(zbx.hosts.get_id(host: @host)).to eq @hostid expect(zbx.hosts.get_id('host' => @host)).to eq @hostid end end describe 'create_or_update' do it 'should return id of updated host' do expect( zbx.hosts.create_or_update( host: @host, interfaces: [ { type: 1, main: 1, ip: '10.20.48.89', port: '10050', useip: 1, dns: '' } ], groups: [groupid: @hostgroupid] ) ).to eq @hostid end end describe 'update' do it 'should return id' do expect( zbx.hosts.update( hostid: @hostid, status: 0 ) ).to eq @hostid end it 'should update groups' do @hostgroupid2 = zbx.hostgroups.create(name: gen_name('hostgroup')) expect( zbx.hosts.update( hostid: @hostid, groups: [groupid: @hostgroupid2] ) ).to eq @hostid expect(zbx.hosts.dump_by_id(hostid: @hostid).first['groups'].first['groupid']).to eq @hostgroupid2.to_s end it 'should update interfaces when use with force: true' do new_ip = '1.2.3.4' zbx.hosts.update( { hostid: @hostid, interfaces: [ { type: 1, main: 1, ip: new_ip, port: '10050', useip: 1, dns: '' } ] }, true ) h = zbx.query( method: 'host.get', params: { hostids: @hostid, selectInterfaces: 'extend' } ).first expect(h['interfaces'].first['ip']).to eq new_ip end end describe 'delete' do it 'HOST: Delete' do expect(zbx.hosts.delete(@hostid)).to eq @hostid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/query.rb
spec/query.rb
require 'spec_helper' describe 'query' do it 'should works' do expect( zbx.query( method: 'host.get', params: { filter: { host: 'asdf' }, selectInterfaces: 'refer' } ) ).to be_kind_of(Array) end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/usermacro.rb
spec/usermacro.rb
require 'spec_helper' describe 'usermacro' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) end context 'when hostmacro not exists' do before do @hostmacro = '{$' + gen_name('HOSTMACRO') + '}' end describe 'create' do it 'should return integer id' do hostmacroid = zbx.usermacros.create( macro: @hostmacro, value: 'public', hostid: @templateid ) expect(hostmacroid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.usermacros.get_id(macro: @hostmacro)).to be_kind_of(NilClass) end end end context 'when hostmacro exists' do before :all do @hostmacro = '{$' + gen_name('HOSTMACRO') + '}' @hostmacroid = zbx.usermacros.create( macro: @hostmacro, value: 'public', hostid: @templateid ) end describe 'get_or_create' do it 'should return id of hostmacro' do expect( zbx.usermacros.get_or_create( macro: @hostmacro, value: 'public', hostid: @templateid ) ).to eq @hostmacroid end end describe 'get_full_data' do it 'should contains created hostmacro' do expect(zbx.usermacros.get_full_data(macro: @hostmacro)[0]).to include('macro' => @hostmacro) end end describe 'get_id' do it 'should return id of hostmacro' do expect(zbx.usermacros.get_id(macro: @hostmacro)).to eq @hostmacroid end end it 'should raise error on no identity given' do expect { zbx.usermacros.get_id({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update' do it 'should return id' do expect( zbx.usermacros.update( hostmacroid: zbx.usermacros.get_id( macro: @hostmacro ), value: 'private' ) ).to eq @hostmacroid end end describe 'create_or_update' do it 'should update existing usermacro' do expect( zbx.usermacros.create_or_update( macro: @hostmacro, value: 'public', hostid: @templateid ) ).to eq @hostmacroid end it 'should create usermacro' do new_hostmacro_id = zbx.usermacros.create_or_update( macro: @hostmacro.gsub(/}/, '____1}'), value: 'public', hostid: @templateid ) expect(new_hostmacro_id).to be_kind_of(Integer) expect(new_hostmacro_id).to be > @hostmacroid end end describe 'delete' do before :all do @result = zbx.usermacros.delete(@hostmacroid) end it 'should return deleted id' do expect(@result).to eq @hostmacroid end it 'should delete item from zabbix' do expect(zbx.usermacros.get_id(macro: @hostmacro)).to be_nil end end end context 'when globalmacro not exists' do before do @globalmacro = '{$' + gen_name('GLOBALMACRO') + '}' end describe 'create_global' do it 'should return integer id' do globalmacroid = zbx.usermacros.create_global( macro: @globalmacro, value: 'public' ) expect(globalmacroid).to be_kind_of(Integer) end end describe 'get_id_global' do it 'should return nil' do expect(zbx.usermacros.get_id_global(macro: @globalmacro)).to be_kind_of(NilClass) end end end context 'when globalmacro exists' do before :all do @globalmacro = '{$' + gen_name('GLOBALMACRO') + '}' @globalmacroid = zbx.usermacros.create_global( macro: @globalmacro, value: 'public' ) end describe 'get_full_data_global' do it 'should contains created globalmacro' do expect(zbx.usermacros.get_full_data_global(macro: @globalmacro)[0]).to include('macro' => @globalmacro) end end describe 'get_id_global' do it 'should return id of globalmacro' do expect(zbx.usermacros.get_id_global(macro: @globalmacro)).to eq @globalmacroid end end it 'should raise error on no identity given' do expect { zbx.usermacros.get_id_global({}) }.to raise_error(ZabbixApi::ApiError) end describe 'update_global' do it 'should return id' do expect( zbx.usermacros.update_global( globalmacroid: zbx.usermacros.get_id_global( macro: @globalmacro ), value: 'private' ) ).to eq @globalmacroid end end describe 'delete_global' do before :all do @result = zbx.usermacros.delete_global(@globalmacroid) end it 'should return deleted id' do expect(@result).to eq @globalmacroid end it 'should delete item from zabbix' do expect(zbx.usermacros.get_id_global(macro: @globalmacro)).to be_nil end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/problem.rb
spec/problem.rb
require 'spec_helper' describe 'problem' do before do @problemdata = { eventid: gen_id.to_s, source: "0", object: "0", objectid: gen_id.to_s, clock: "1611856476", ns: "183091100", r_eventid: "0", r_clock: "0", r_ns: "0", correlationid: "0", userid: "0", name: "Zabbix agent is not available (for 3m)", acknowledged: "0", severity: "3", opdata: "", acknowledges: [], suppression_data: [], suppressed: "0", urls: [], tags: [] } end context 'when incorrect method' do describe 'create' do it 'should raise ApiError' do expect{zbx.problems.create({})}. to raise_error(ZabbixApi::ApiError, /.*\"data\": \"Incorrect method \\\"problem.create\\\"\.\"/) end end describe 'delete' do it 'should raise ApiError' do expect{zbx.problems.delete({})}. to raise_error(ZabbixApi::ApiError, /.*\"data\": \"Incorrect method \\\"problem.delete\\\"\.\"/) end end # describe 'update' do # it 'should raise ApiError' do # expect{zbx.problems.update({name: gen_name("problem")})}. # to raise_error(ZabbixApi::ApiError, /.*\"data\": \"Incorrect method \\\"problem.update\\\"\.\"/) # end # end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/drule.rb
spec/drule.rb
# encoding: utf-8 require 'spec_helper' describe 'drule' do before do @drulename = gen_name 'drule' @usergroupid = zbx.usergroups.create(:name => gen_name('usergroup')) @dcheckdata = [{ :type => '9', # zabbix agent :uniq => '0', # (default) do not use this check as a uniqueness criteria :key_ => 'system.hostname', :ports => '10050', }] @druledata = { :name => @drulename, :delay => '60', :status => '0', # action is enabled :iprange => '192.168.0.0/24', # iprange to discover zabbix agents in :dchecks => @dcheckdata, } end context 'when not exists' do describe 'create' do it 'should return integer id' do druleid = zbx.drules.create(@druledata) expect(druleid).to be_kind_of(Integer) end end end context 'when exists' do before do @druleid = zbx.drules.create(@druledata) end describe 'create_or_update' do it 'should return id' do expect(zbx.drules.create_or_update(@druledata)).to eq @druleid end end describe 'delete' do it 'should return id' do expect(zbx.drules.delete(@druleid)).to eq @druleid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/configuration.rb
spec/configuration.rb
require 'spec_helper' describe 'configuration' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroup_id = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @template_id = zbx.templates.create( host: @template, groups: [groupid: @hostgroup_id] ) @source = zbx.configurations.export( format: 'xml', options: { templates: [@template_id] } ) @item = gen_name 'item' @item_id = zbx.items.create( name: @item, description: 'item', key_: 'proc.num[aaa]', type: 0, value_type: 3, hostid: zbx.templates.get_id(host: @template) ) end after :all do zbx.items.delete(zbx.items.get_id(name: @item)) zbx.templates.delete(zbx.templates.get_id(host: @template)) zbx.hostgroups.delete(zbx.hostgroups.get_id(name: @hostgroup)) end context 'when object not exists' do describe 'import with createMissing' do before do zbx.items.delete(@item_id) zbx.templates.delete(@template_id) zbx.hostgroups.delete(@hostgroup_id) zbx.configurations.import( format: 'xml', rules: { groups: { createMissing: true }, templates: { createMissing: true } }, source: @source ) end it 'should create object' do expect(zbx.hostgroups.get_id(name: @hostgroup)).to be_kind_of(Integer) expect(zbx.templates.get_id(host: @template)).to be_kind_of(Integer) end end end context 'when object exists' do describe 'export' do before do zbx.items.create( name: @item, description: 'item', key_: 'proc.num[aaa]', type: 0, value_type: 3, hostid: zbx.templates.get_id(host: @template) ) end it 'should export updated object' do expect( zbx.configurations.export( format: 'xml', options: { templates: [zbx.templates.get_id(host: @template)] } ) ).to match(/#{@item}/) end end describe 'import with updateExisting' do before do @source_updated = zbx.configurations.export( format: 'xml', options: { templates: [zbx.templates.get_id(host: @template)] } ) zbx.items.delete(zbx.items.get_id(name: @item)) zbx.configurations.import( format: 'xml', rules: { templates: { updateExisting: true }, items: { createMissing: true } }, source: @source_updated ) end it 'should update object' do expect( zbx.configurations.export( format: 'xml', options: { templates: [zbx.templates.get_id(host: @template)] } ) ).to match(/#{@item}/) end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/template.rb
spec/template.rb
require 'spec_helper' describe 'template' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) end context 'when name not exists' do before do @template = gen_name 'template' end describe 'create' do it 'should return integer id' do templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) expect(templateid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.templates.get_id(host: @template)).to be_kind_of(NilClass) end end end context 'when name exists' do before :all do @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) end describe 'get_or_create' do it 'should return id of template' do expect( zbx.templates.get_or_create( host: @template, groups: [groupid: @hostgroupid] ) ).to eq @templateid end end describe 'get_full_data' do it 'should contains created template' do expect(zbx.templates.get_full_data(host: @template)[0]).to include('host' => @template) end end describe 'get_id' do it 'should return id of template' do expect(zbx.templates.get_id(host: @template)).to eq @templateid end end describe 'all' do it 'should contains template' do expect(zbx.templates.all).to include(@template => @templateid.to_s) end end describe 'delete' do it 'should return id' do template = gen_name 'template' templateid = zbx.templates.create( host: template, groups: [groupid: @hostgroupid] ) expect(zbx.templates.delete(templateid)).to eq templateid end end context 'host related operations' do before :all do @host = gen_name 'host' @hostid = zbx.hosts.create( host: @host, interfaces: [ { type: 1, main: 1, ip: '10.20.48.88', dns: '', port: '10050', useip: 1 } ], groups: [groupid: @hostgroupid] ) end context 'not linked with host' do describe 'mass_update' do it 'should return true' do expect( zbx.templates.mass_update( hosts_id: [@hostid], templates_id: [@templateid] ) ).to be true end end end context 'linked with host' do before :all do zbx.templates.mass_update( hosts_id: [@hostid], templates_id: [@templateid] ) end describe 'get_ids_by_host' do it 'should contains id of linked template' do tmpl_array = zbx.templates.get_ids_by_host( hostids: [@hostid] ) expect(tmpl_array).to be_kind_of(Array) expect(tmpl_array).to include @templateid.to_s end end describe 'mass_add' do it 'should return true' do expect( zbx.templates.mass_add( hosts_id: [@hostid], templates_id: [@templateid] ) ).to be_kind_of(TrueClass) end end describe 'mass_remove' do it 'should return true' do expect( zbx.templates.mass_remove( hosts_id: [@hostid], templates_id: [@templateid] ) ).to be true end end end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/hostgroup.rb
spec/hostgroup.rb
require 'spec_helper' describe 'hostgroup' do context 'when not exists' do describe 'create' do it 'should return integer id after creation' do hostgroupid = zbx.hostgroups.create(name: "hostgroup_#{rand(1_000_000)}") expect(hostgroupid).to be_kind_of(Integer) end end end context 'when exists' do before :all do @hostgroup = gen_name('hostgroup') @hostgroupid = zbx.hostgroups.create(name: @hostgroup) end describe 'get_id' do it 'should return id' do expect(zbx.hostgroups.get_id(name: @hostgroup)).to eq @hostgroupid end it 'should return nil for not existing group' do expect(zbx.hostgroups.get_id(name: "#{@hostgroup}______")).to be_kind_of(NilClass) end end describe 'get_or_create' do it 'should return id of existing hostgroup' do expect(zbx.hostgroups.get_or_create(name: @hostgroup)).to eq @hostgroupid end end describe 'create_or_update' do it 'should return id of hostgroup' do expect(zbx.hostgroups.create_or_update(name: @hostgroup)).to eq @hostgroupid end end describe 'all' do it 'should contains created hostgroup' do expect(zbx.hostgroups.all).to include(@hostgroup => @hostgroupid.to_s) end end describe 'delete' do it 'shold return id' do expect(zbx.hostgroups.delete(@hostgroupid)).to eq @hostgroupid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/valuemap.rb
spec/valuemap.rb
require 'spec_helper' describe 'valuemap' do before :all do @valuemap = gen_name 'valuemap' end context 'when not exists' do describe 'create' do it 'should return an integer id' do valuemapid = zbx.valuemaps.create_or_update( name: @valuemap, mappings: [ 'newvalue' => 'test', 'value' => 'test' ] ) expect(valuemapid).to be_kind_of(Integer) end end end context 'when exists' do before do @valuemapid = zbx.valuemaps.create_or_update( name: @valuemap, mappings: [ 'newvalue' => 'test', 'value' => 'test' ] ) end describe 'create_or_update' do it 'should return id' do expect( zbx.valuemaps.create_or_update( name: @valuemap, mappings: [ 'newvalue' => 'test', 'value' => 'test' ] ) ).to eq @valuemapid end it 'should return id' do expect(@valuemapid).to eq @valuemapid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/server.rb
spec/server.rb
require 'spec_helper' describe 'server' do describe 'version' do it 'should be string' do expect(zbx.server.version).to be_kind_of(String) end it 'should be 2.4.x, 3.2.x, 3.4.x, 4.0.x, 5.0.x, or 5.2.x' do expect(zbx.server.version).to match(/(2\.4|3\.[024]|4\.0|5\.[02])\.\d+/) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/screen.rb
spec/screen.rb
require 'spec_helper' describe 'screen' do before :all do @hostgroup = gen_name 'hostgroup' @hostgroupid = zbx.hostgroups.create(name: @hostgroup) @template = gen_name 'template' @templateid = zbx.templates.create( host: @template, groups: [groupid: @hostgroupid] ) @application = gen_name 'application' @applicationid = zbx.applications.create( name: @application, hostid: @templateid ) @item = gen_name 'item' @itemid = zbx.items.create( name: @item, key_: "proc.num[#{gen_name 'proc'}]", status: 0, hostid: @templateid, applications: [@applicationid] ) @color = '123456' @gitems = { itemid: @itemid, calc_fnc: '3', color: @color, type: '0', periods_cnt: '5' } @graph = gen_name 'graph' @graphid = zbx.graphs.create( gitems: [@gitems], show_triggers: '0', name: @graph, width: '900', height: '200' ) @screen_name = gen_name 'screen' end context 'when not exists' do describe 'get_or_create_for_host' do it 'should return id' do screenid = zbx.screens.get_or_create_for_host( screen_name: @screen_name, graphids: [@graphid] ) expect(screenid).to be_kind_of(Integer) end end end context 'when exists' do before do @screen_name = gen_name 'screen' @screenid = zbx.screens.get_or_create_for_host( screen_name: @screen_name, graphids: [@graphid] ) end describe 'get_or_create_for_host' do it 'should return id' do screenid = zbx.screens.get_or_create_for_host( screen_name: @screen_name, graphids: [@graphid] ) expect(screenid).to eq @screenid end end describe 'delete' do it 'should return id' do expect(zbx.screens.delete(@screenid)).to eq @screenid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/mediatype.rb
spec/mediatype.rb
require 'spec_helper' describe 'mediatype' do before do @mediatype = gen_name 'mediatype' end context 'when not exists' do describe 'create' do it 'should return integer id' do mediatypeid = zbx.mediatypes.create( name: @mediatype, type: 0, smtp_server: '127.0.0.1', smtp_email: 'zabbix@test.com', smtp_helo: 'test.com' ) expect(mediatypeid).to be_kind_of(Integer) end end end context 'when exists' do before do @mediatypeid = zbx.mediatypes.create( name: @mediatype, type: 0, smtp_server: '127.0.0.1', smtp_email: 'zabbix@test.com', smtp_helo: 'test.com' ) end describe 'create_or_update' do it 'should return id' do expect( zbx.mediatypes.create_or_update( name: @mediatype, smtp_email: 'zabbix2@test.com', smtp_helo: 'test.com' ) ).to eq @mediatypeid end it 'should return id' do expect(@mediatypeid).to eq @mediatypeid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/spec_helper.rb
spec/spec_helper.rb
require 'zabbixapi' def zbx # settings @api_url = ENV['ZABBIX_HOST_URL'] || 'http://localhost:8080/api_jsonrpc.php' @api_login = ENV['ZABBIX_USERNAME'] || 'Admin' @api_password = ENV['ZABBIX_PASSWORD'] || 'zabbix' @zbx ||= ZabbixApi.connect( url: @api_url, user: @api_login, password: @api_password, debug: ENV['ZABBIX_DEBUG'] ? true : false ) end def gen_id rand(1_000_000_000) end def gen_name(prefix) suffix = rand(1_000_000_000) "#{prefix}_#{suffix}" end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/action.rb
spec/action.rb
require 'spec_helper' describe 'action' do before do @actionname = gen_name 'action' @usergroupid = zbx.usergroups.create(name: gen_name('usergroup')) @actiondata = { name: @actionname, eventsource: '0', # event source is a triggerid status: '0', # action is enabled esc_period: '120', # how long each step should take def_shortdata: 'Email header', def_longdata: 'Email content', maintenance_mode: '1', filter: { evaltype: '1', # perform 'and' between the conditions conditions: [ { conditiontype: '3', # trigger name operator: '2', # like value: 'pattern' # the pattern }, { conditiontype: '4', # trigger severity operator: '5', # >= value: '3' # average } ] }, operations: [ { operationtype: '0', # send message opmessage_grp: [ # who the message will be sent to { usrgrpid: @usergroupid } ], opmessage: { default_msg: '0', # use default message mediatypeid: '1' # email id } } ], recovery_operations: [ { operationtype: '11', # send recovery message opmessage_grp: [ # who the message will be sent to { usrgrpid: @usergroupid } ], opmessage: { default_msg: '0', # use default message mediatypeid: '1' # email id } } ] } end context 'when not exists' do describe 'create' do it 'should return integer id' do actionid = zbx.actions.create(@actiondata) expect(actionid).to be_kind_of(Integer) end end end context 'when exists' do before do @actionid = zbx.actions.create(@actiondata) end describe 'create_or_update' do it 'should return id' do expect(zbx.actions.create_or_update(@actiondata)).to eq @actionid end end describe 'delete' do it 'should return id' do expect(zbx.actions.delete(@actionid)).to eq @actionid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/user.rb
spec/user.rb
require 'spec_helper' describe 'user' do before :all do @usergroup = gen_name 'usergroup' @usergroupid = { usrgrpid: zbx.usergroups.create(name: @usergroup), } @roleid = "1" puts "USERGROUPID: #{@usergroupid}" @mediatype = gen_name 'mediatype' @mediatypeid = zbx.mediatypes.create( name: @mediatype, type: 0, smtp_server: '127.0.0.1', smtp_email: 'zabbix@test.com', smtp_helo: 'test.com' ) end def media { mediatypeid: @mediatypeid, sendto: ['test@test.com'], active: 0, period: '1-7,00:00-24:00', severity: '56' } end context 'when not exists' do describe 'create' do it 'should return integer id' do user = gen_name 'user' userid = zbx.users.create( alias: user, name: user, surname: user, passwd: user, roleid: @roleid, usrgrps: [@usergroupid] ) expect(userid).to be_kind_of(Integer) end end describe 'get_id' do it 'should return nil' do expect(zbx.users.get_id(alias: 'name_____')).to be_nil end end end context 'when exists' do before :all do @user = gen_name 'user' @userid = zbx.users.create( alias: @user, name: @user, surname: @user, passwd: @user, usrgrps: [@usergroupid], roleid: @roleid ) end describe 'create_or_update' do it 'should return id' do expect( zbx.users.create_or_update( alias: @user, name: @user, surname: @user, passwd: @user, roleid: @roleid ) ).to eq @userid end end describe 'get_full_data' do it 'should return string name' do expect(zbx.users.get_full_data(alias: @user)[0]['name']).to be_kind_of(String) end end describe 'update' do it 'should return id' do expect(zbx.users.update(userid: @userid, name: gen_name('user'))).to eq @userid end end describe 'update by adding media' do it 'should return id' do expect( zbx.users.add_medias( userids: [@userid], media: [media] ) ).to be_kind_of(Integer) end end describe 'update_medias' do it 'should return the user id' do # Call twice to ensure update_medias first successfully creates the media, then updates it 2.times do returned_userid = zbx.users.update_medias( userids: [@userid], media: [media] ) expect(returned_userid).to eq @userid end end end describe 'delete' do it 'should return id' do expect(zbx.users.delete(@userid)).to eq @userid end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/client_spec.rb
spec/zabbixapi/client_spec.rb
require 'spec_helper' describe 'ZabbixApi::Client' do let(:client_mock) { ZabbixApi::Client.new(options) } let(:options) { {} } let(:auth) { double } let(:api_version) { '5.2.2' } describe '.id' do subject { client_mock.id } before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') end it { is_expected.to be_kind_of Integer } it 'be in between 0 to 100_000' do expect_any_instance_of(ZabbixApi::Client).to receive(:rand).with(100_000) subject end end describe '.api_version' do subject { client_mock } before do allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'apiinfo.version', params: {} ).and_return('5.2.2') end it 'gets version using api_request ' do expect_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'apiinfo.version', params: {} ) subject end context 'when api_version is already set' do before do client_mock.instance_variable_set(:@api_version, '5.2.2') end it 'does not request an api for version ' do expect_any_instance_of(ZabbixApi::Client).not_to receive(:api_request).with( method: 'apiinfo.version', params: {} ) subject end end end describe '.auth' do subject { client_mock } before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.login', params: { user: nil, password: nil } ) end it 'gets auth using api request' do expect_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.login', params: { user: nil, password: nil } ) subject end end describe '.logout' do subject { client_mock.logout() } before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.login', params: { user: nil, password: nil } ) allow_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.logout' ) end it 'revokes auth using api request' do expect_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.logout', params: [] ) subject end end describe '.initialize' do subject { client_mock } before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return(api_version) allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') allow_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.login', params: { user: nil, password: nil } ) allow_any_instance_of(ZabbixApi::Client).to receive(:api_request).with( method: 'user.logout', params: {} ) end context 'when proxy is provided and no_proxy flag is false' do let(:options) do { no_proxy: false } end before { allow(ENV).to receive(:[]).with('http_proxy').and_return('https://username:password@www.cerner.com') } it 'sets proxy class variables' do expect(subject.instance_variable_get(:@proxy_uri)).to be_kind_of(URI::HTTPS) expect(subject.instance_variable_get(:@proxy_host)).to eq('www.cerner.com') expect(subject.instance_variable_get(:@proxy_port)).to eq(443) expect(subject.instance_variable_get(:@proxy_user)).to eq('username') expect(subject.instance_variable_get(:@proxy_pass)).to eq('password') end it 'sets auth_hash' do expect(subject.instance_variable_get(:@auth_hash)).to eq('auth') end end context 'when proxy is provided and no_proxy flag is true' do let(:options) do { no_proxy: true } end before { allow(ENV).to receive(:[]).with('http_proxy').and_return('https://username:password@www.cerner.com') } it 'does not proxy class variables' do expect(subject.instance_variable_get(:@proxy_uri)).not_to be_kind_of(URI::HTTPS) expect(subject.instance_variable_get(:@proxy_host)).not_to eq('www.cerner.com') expect(subject.instance_variable_get(:@proxy_port)).not_to eq(443) expect(subject.instance_variable_get(:@proxy_user)).not_to eq('username') expect(subject.instance_variable_get(:@proxy_pass)).not_to eq('password') end it 'sets auth_hash' do expect(subject.instance_variable_get(:@auth_hash)).to eq('auth') end end context 'when proxy is not provided and no_proxy flag is false' do let(:options) do { no_proxy: false } end before { allow(ENV).to receive(:[]).with('http_proxy').and_return(nil) } it 'does not proxy class variables' do expect(subject.instance_variable_get(:@proxy_uri)).to be_nil expect(subject.instance_variable_get(:@proxy_host)).not_to eq('www.cerner.com') expect(subject.instance_variable_get(:@proxy_port)).not_to eq(443) expect(subject.instance_variable_get(:@proxy_user)).not_to eq('username') expect(subject.instance_variable_get(:@proxy_pass)).not_to eq('password') end it 'sets auth_hash' do expect(subject.instance_variable_get(:@auth_hash)).to eq('auth') end end context 'when major api_version is not supported' do let(:api_version) { 'not_a_valid_version' } before { allow(ENV).to receive(:[]).with('http_proxy').and_return(nil) } it 'raises ApiError' do expect { subject }.to raise_error(ZabbixApi::ApiError, "Zabbix API version: #{api_version} is not supported by this version of zabbixapi") end end context 'when major api_version is not supported, but ignored' do let(:options) do { ignore_version: true } end let(:api_version) { 'not_a_valid_version' } before { allow(ENV).to receive(:[]).with('http_proxy').and_return(nil) } it 'sets auth_hash' do expect(subject.instance_variable_get(:@auth_hash)).to eq('auth') end end end describe '.message_json' do subject { client_mock.message_json(body) } let(:id) { 9090 } let(:generated_json) { { test: 'testjson' } } let(:method) { 'apiinfo.version' } let(:body) do { method: method, params: 'testparams' } end let(:message) do { method: method, params: 'testparams', id: id, jsonrpc: '2.0' } end before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') allow_any_instance_of(ZabbixApi::Client).to receive(:id).and_return(id) allow(JSON).to receive(:generate).with(message).and_return(generated_json) end context 'when method is apiinfo.version' do it 'adds auth information before generating json' do expect(subject).to eq generated_json end end context 'when method is user.login' do let(:method) { 'user.login' } it 'adds auth information before generating json' do expect(subject).to eq generated_json end end context 'when method is not `apiinfo.version` or `user.login` or `user.logout`' do let(:method) { 'fakemethod' } let(:message) do { method: method, params: 'testparams', id: id, jsonrpc: '2.0', auth: 'auth' } end it 'adds auth information before generating json' do expect(subject).to eq generated_json end end end describe '.http_request' do subject { client_mock.http_request(body) } let(:mock_post) { double } let(:http_mock) { double } let(:http_proxy) { double } let(:timeout) { 60 } let(:response_code) { '200' } let(:response) { instance_double('HTTP::Response', code: response_code, body: { test: 'testbody' }) } let(:options) do { no_proxy: false, url: 'https://username:password@www.cerner.com' } end let(:body) { 'testbody ' } before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') allow(Net::HTTP).to receive(:Proxy).with( 'www.cerner.com', 443, 'username', 'password' ).and_return(http_proxy) allow(http_proxy).to receive(:new).with( 'www.cerner.com', 443 ).and_return(http_mock) allow(ENV).to receive(:[]) .with('http_proxy').and_return('https://username:password@www.cerner.com') allow(Net::HTTP::Post).to receive(:new).with('/').and_return(mock_post) allow(mock_post).to receive(:basic_auth).with('username', 'password') allow(mock_post).to receive(:add_field).with('Content-Type', 'application/json-rpc') allow(mock_post).to receive(:body=).with(body) allow(http_mock).to receive(:request).with(mock_post).and_return(response) allow(http_mock).to receive(:use_ssl=).with(true) allow(http_mock).to receive(:verify_mode=).with(0) allow(http_mock).to receive(:open_timeout=).with(timeout) allow(http_mock).to receive(:read_timeout=).with(timeout) allow(OpenSSL::SSL).to receive(:VERIFY_NONE).and_return(true) allow(response).to receive(:[]).with('error').and_return('Test error') end context 'when response code is 200' do it 'returns the response body' do expect(subject).to eq(test: 'testbody') end end context 'when response code is not 200' do let(:response_code) { '404' } it 'raises HttpError' do expect { subject }.to raise_error(ZabbixApi::HttpError, "HTTP Error: #{response_code} on #{options[:url]}") end end context 'when timeout is given as an option' do let(:timeout) { 300 } let(:options) do { no_proxy: false, url: 'https://username:password@www.cerner.com', timeout: timeout } end it 'sets provided timeout' do expect(http_mock).to receive(:open_timeout=).with(timeout) expect(http_mock).to receive(:read_timeout=).with(timeout) subject end end context 'when proxy_uri is not provided' do let(:options) do { no_proxy: true, url: 'https://username:password@www.cerner.com' } end before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') allow(Net::HTTP).to receive(:new).with( 'www.cerner.com', 443 ).and_return(http_mock) end it 'create http object without proxy' do expect(Net::HTTP).not_to receive(:Proxy).with( 'www.cerner.com', 443, 'username', 'password' ) subject end end context 'when debug is set to true' do let(:options) do { no_proxy: false, url: 'https://username:password@www.cerner.com', debug: true } end before do allow_any_instance_of(ZabbixApi::Client).to receive(:puts) end it 'logs messages' do expect_any_instance_of(ZabbixApi::Client).to receive(:puts) .with("[DEBUG] Timeout for request set to #{timeout} seconds") expect_any_instance_of(ZabbixApi::Client).to receive(:puts) .with("[DEBUG] Get answer: #{response.body}") subject end end end describe '._request' do subject { client_mock._request(body) } let(:options) { { debug: true } } let(:response) { double } let(:body) do { params: 'testparams' } end let(:result) do { 'result' => 'testresult' } end before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') allow_any_instance_of(ZabbixApi::Client).to receive(:pretty_body) allow_any_instance_of(ZabbixApi::Client).to receive(:http_request).with(body).and_return(response) allow(JSON).to receive(:parse).with(response).and_return(result) end before do allow_any_instance_of(ZabbixApi::Client).to receive(:puts) end it 'logs DEBUG message' do expect_any_instance_of(ZabbixApi::Client).to receive(:puts) .with("[DEBUG] Send request: #{body}") subject end it 'returns result from the response' do expect(subject).to eq 'testresult' end context 'when result contains error' do let(:result) do { 'error' => 'testresult' } end it 'raises ApiError' do expect { subject }.to raise_error(ZabbixApi::ApiError, /Server answer API error/) end end end describe '.pretty_body' do subject { client_mock.pretty_body(body) } let(:body) do "{ \"params\": \"testparams\" }" end let(:parsed_body) do "{\n \"params\": \"testparams\"\n}" end let(:result) do { 'result' => 'testresult' } end before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') end context 'when body doesn not contain password as param' do it 'returns unparsed body' do expect(subject).to eq parsed_body end end context 'when body contains password as param' do let(:body) do "{ \"params\": { \"password\": \"123pass\"} }" end let(:parsed_body) do "{\n \"params\": {\n \"password\": \"***\"\n }\n}" end it 'changes password to `***`' do expect(subject).to eq parsed_body end end end describe '.api_request' do subject { client_mock.api_request(body) } let(:body) do "{ \"params\": \"testparams\" }" end let(:message_json) do "{\n \"params\": \"testparams\"\n}" end let(:result) do { 'result' => 'testresult' } end before do allow_any_instance_of(ZabbixApi::Client).to receive(:api_version).and_return('5.2.2') allow_any_instance_of(ZabbixApi::Client).to receive(:auth).and_return('auth') allow_any_instance_of(ZabbixApi::Client).to receive(:message_json).with(body).and_return(message_json) allow_any_instance_of(ZabbixApi::Client).to receive(:_request).with(message_json).and_return(result) end it { is_expected.to eq result } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/basic/basic_func_spec.rb
spec/zabbixapi/basic/basic_func_spec.rb
require 'spec_helper' describe 'ZabbixApi::Basic' do let(:basic_mock) { ZabbixApi::Basic.new(client) } let(:client) { double } describe '.log' do subject { basic_mock.log(message) } let(:message) { 'test-message' } let(:debug) { true } let(:client) { instance_double('ZabbixApi::Client', options: { debug: debug }) } context 'when debug is set to true' do it 'prints the message' do expect(basic_mock).to receive(:puts).with(message) subject end end context 'when debug is set to false' do let(:debug) { false } it 'does not print the message' do expect(basic_mock).not_to receive(:puts).with(message) subject end end end describe '.symbolize_keys' do subject { basic_mock.symbolize_keys(object) } let(:object) { { 'test' => { 'one' => 1, 'two' => [1, 2] } } } let(:symbolized_object) { { test: { one: 1, two: [1, 2] } } } context 'when hash with string keys is passed' do it 'converts all the string keys to symbol' do expect(subject).to eq symbolized_object end end context 'when string object is passed' do let(:object) { 'test-this' } let(:symbolized_object) { 'test-this' } it 'returns the same object back' do expect(subject).to eq symbolized_object end end context 'when nil object is passed' do let(:object) { nil } let(:symbolized_object) { nil } it 'returns nil back' do expect(subject).to eq symbolized_object end end end describe '.normalize_hash' do subject { basic_mock.normalize_hash(hash) } let(:hash) { { 'one' => 1, 'two' => [1, 2] } } let(:hash_dup) { { 'one' => 1, 'two' => [1, 2] } } let(:symbolized_object) { { 'one' => '1', 'two' => normalized_array } } let(:normalized_array) { %w[1 2] } before do allow(basic_mock).to receive(:normalized_array).with([1, 2]).and_return(normalized_array) allow(hash).to receive(:dup).and_return(hash_dup) end context 'when hash is passed' do it 'normalizes the hash' do expect(subject).to eq symbolized_object end it 'duplicates the hash before modifying' do expect(hash).to receive(:dup) subject end end context 'when passed hash contains key hostid' do let(:hash) { { one: 1, two: [1, 2], hostid: 3 } } let(:hash_dup) { { one: 1, two: [1, 2], hostid: 3 } } let(:symbolized_object) { { one: '1', two: %w[1 2] } } it 'deletes hostid from hash during normalization' do expect(subject).to eq symbolized_object end end end describe '.normalize_array' do subject { basic_mock.normalize_array(array) } let(:array) { ['one', [2, 3], { four: 5 }] } let(:normalized_array) { ['one', %w[2 3], normalized_hash] } let(:normalized_hash) { { four: '5' } } before do allow(basic_mock).to receive(:normalize_hash).with(four: 5).and_return(normalized_hash) end context 'when array is passed' do it 'normalizes the array' do expect(subject).to eq normalized_array end end end describe '.parse_keys' do subject { basic_mock.parse_keys(data) } let(:data) { { test: ['1'] } } let(:expected) { 1 } before do allow(basic_mock).to receive(:keys).and_return(:test) end context 'when hash is passed' do it 'returns the object id' do expect(subject).to eq expected end end context 'when passed hash is empty' do let(:data) { {} } it { is_expected.to be_nil } end context 'when TrueClass is passed' do let(:data) { true } it { is_expected.to be_truthy } end context 'when FalseClass is passed' do let(:data) { false } it { is_expected.to be_falsy } end end describe '.merge_params' do subject { basic_mock.merge_params(first_hash, second_hash) } let(:first_hash) { { test1: 1 } } let(:first_hash_dup) { { test1: 1 } } let(:second_hash) { { test2: 2 } } let(:expected) { { test1: 1, test2: 2 } } before { allow(first_hash).to receive(:dup).and_return(first_hash_dup) } it { is_expected.to eq expected } it 'merged two hashes in new hash object' do expect(first_hash).to receive(:dup) subject end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/basic/basic_alias_spec.rb
spec/zabbixapi/basic/basic_alias_spec.rb
require 'spec_helper' describe 'ZabbixApi::Basic' do let(:basic_mock) { ZabbixApi::Basic.new(client) } let(:client) { double('mock_client', options: {}, api_request: {} ) } let(:data) { {} } after { subject } describe '.get' do subject { basic_mock.get(data) } before do allow(basic_mock).to receive(:get_full_data).with(data) allow(basic_mock).to receive(:method_name) end it 'calls get_full_data' do expect(basic_mock).to receive(:get_full_data).with(data) end end describe '.add' do subject { basic_mock.add(data) } before { allow(basic_mock).to receive(:create).with(data) } it 'calls create' do expect(basic_mock).to receive(:create).with(data) end end describe '.destroy' do subject { basic_mock.destroy(data) } before { allow(basic_mock).to receive(:delete).with(data) } it 'calls delete' do expect(basic_mock).to receive(:delete).with(data) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/basic/basic_logic_spec.rb
spec/zabbixapi/basic/basic_logic_spec.rb
require 'spec_helper' describe 'ZabbixApi::Basic' do let(:basic_mock) { ZabbixApi::Basic.new(client) } let(:client) { double } let(:method_name) { 'test-method' } let(:default_options) { {} } let(:data_create) { [data] } let(:result) { 'test-result' } let(:method) { "#{method_name}.#{operation_name}" } let(:operation_name) { 'dummy' } before do allow(basic_mock).to receive(:log) allow(basic_mock).to receive(:method_name).and_return(method_name) allow(basic_mock).to receive(:default_options).and_return(default_options) allow(client).to receive(:api_request).with(method: method, params: data_create).and_return(result) allow(basic_mock).to receive(:parse_keys) end describe '.create' do subject { basic_mock.create(data) } let(:data) { { test: 1 } } let(:operation_name) { 'create' } it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call create with parameters: #{data.inspect}") subject end it 'prints the result' do expect(basic_mock).to receive(:parse_keys).with(result) subject end context 'when default_options is not empty' do let(:default_options) { { test2: 2 } } let(:data_create) { [{ test: 1, test2: 2 }] } it 'merges data with default options' do expect(client).to receive(:api_request) .with(method: 'test-method.create', params: data_create) subject end end end describe '.delete' do subject { basic_mock.delete(data) } let(:data) { { test: 1 } } let(:operation_name) { 'delete' } it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call delete with parameters: #{data.inspect}") subject end it 'prints the result' do expect(basic_mock).to receive(:parse_keys).with(result) subject end end describe '.create_or_update' do subject { basic_mock.create_or_update(data) } let(:data) { { test: 1 } } let(:identify) { 'test' } let(:id) { 1 } before do allow(basic_mock).to receive(:identify).and_return(identify) allow(basic_mock).to receive(:get_id).with(test: 1).and_return(id) allow(basic_mock).to receive(:update) allow(basic_mock).to receive(:create) allow(basic_mock).to receive(:key).and_return('key') end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call create_or_update with parameters: #{data.inspect}") subject end context 'when ID already exists' do it 'calls update' do expect(basic_mock).to receive(:update).with(test: 1, key: '1') subject end end context 'when ID does not exist' do let(:id) { nil } it 'calls create' do expect(basic_mock).to receive(:create).with(data) subject end end end describe '.update' do subject { basic_mock.update(data, force) } let(:data) { { test: '1' } } let(:force) { false } let(:id_hash) { [{ 'test' => 1 }, { 'test2' => 2 }] } let(:dump) { { test: '1' } } let(:hash_equals) { true } let(:operation_name) { 'update' } before do allow(basic_mock).to receive(:dump_by_id).with(test: '1').and_return(id_hash) allow(basic_mock).to receive(:symbolize_keys).with('test' => 1).and_return(test: '1') allow(basic_mock).to receive(:hash_equals?).with(dump, data).and_return(hash_equals) allow(basic_mock).to receive(:key).and_return('test') end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call update with parameters: #{data.inspect}") subject end context 'when dump and data are equal and force set to false' do it 'logs message' do expect(basic_mock).to receive(:log).with("[DEBUG] Equal keys #{dump} and #{data}, skip update") subject end it 'returns the integer data value based on key' do expect(subject).to eq 1 end end context 'when dump and data are equal and force set to true' do let(:force) { true } it 'parses the result from the api request' do expect(basic_mock).to receive(:parse_keys).with(result) subject end end context 'when dump and data are not equal and force set to false' do let(:hash_equals) { false } it 'parses the result from the api request' do expect(basic_mock).to receive(:parse_keys).with(result) subject end end end describe '.get_full_data' do subject { basic_mock.get_full_data(data) } let(:data) { { testidentify: '1' } } let(:result) { [{ result: 'helloworld' }] } let(:identify) { 'testidentify' } before do allow(basic_mock).to receive(:identify).and_return(identify) allow(client).to receive(:api_request).with( method: "#{method_name}.get", params: { filter: { testidentify: '1' }, output: 'extend' } ).and_return(result) end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call get_full_data with parameters: #{data.inspect}") subject end context 'when api request is successful' do it 'returns an array of hash return by an API' do expect(subject).to eq result end end end describe '.get_raw' do subject { basic_mock.get_raw(data) } let(:data) { { testidentify: '1' } } let(:result) { [{ result: 'helloworld' }] } let(:identify) { 'testidentify' } before do allow(basic_mock).to receive(:identify).and_return(identify) allow(client).to receive(:api_request).with( method: "#{method_name}.get", params: data ).and_return(result) end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call get_raw with parameters: #{data.inspect}") subject end context 'when api request is successful' do it 'returns an array of hash return by an API' do expect(subject).to eq result end end end describe '.dump_by_id' do subject { basic_mock.dump_by_id(data) } let(:data) { { testkey: '1' } } let(:result) { [{ result: 'helloworld' }] } let(:key) { 'testkey' } before do allow(basic_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: "#{method_name}.get", params: { filter: { testkey: '1' }, output: 'extend' } ).and_return(result) end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call dump_by_id with parameters: #{data.inspect}") subject end context 'when api request is successful' do it 'returns an array of hash return by an API' do expect(subject).to eq result end end end describe '.all' do subject { basic_mock.all } let(:data) { { testkey: '1' } } let(:result) { [{ 'testkey' => '1', 'testidentify' => 2 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:expected) { { 2 => '1' } } before do allow(basic_mock).to receive(:key).and_return(key) allow(basic_mock).to receive(:identify).and_return(identify) allow(client).to receive(:api_request).with( method: "#{method_name}.get", params: { output: 'extend' } ).and_return(result) end context 'when api request is successful' do it 'returns an array of hash return by an API' do expect(subject).to eq expected end end end describe '.get_id' do subject { basic_mock.get_id(data) } let(:data) { { 'testidentify' => 1 } } let(:symbolized_data) { { testidentify: 1 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { 111 } before do allow(basic_mock).to receive(:key).and_return(key) allow(basic_mock).to receive(:identify).and_return(identify) allow(basic_mock).to receive(:symbolize_keys).with(data).and_return(symbolized_data) allow(client).to receive(:api_request).with( method: "#{method_name}.get", params: { filter: symbolized_data, output: [key, identify] } ).and_return(result) end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call get_id with parameters: #{data.inspect}") subject end context 'when data has `identify` as a key' do it 'symbolizes the data' do expect(basic_mock).to receive(:symbolize_keys).with(data) subject end it 'returns the id from the response' do expect(subject).to eq id end end context 'when data does not have `identify` as a key' do let(:identify) { 'wrongtestidentify' } it 'symbolizes the data' do expect(basic_mock).not_to receive(:symbolize_keys).with(data) expect { subject }.to raise_error(ZabbixApi::ApiError, "#{identify} not supplied in call to get_id") end end end describe '.get_or_create' do subject { basic_mock.get_or_create(data) } let(:data) { { testidentify: 1 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { nil } let(:id_through_create) { 222 } before do allow(basic_mock).to receive(:identify).and_return(identify) allow(basic_mock).to receive(:get_id).with(testidentify: 1).and_return(id) allow(basic_mock).to receive(:create).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(basic_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/basic/basic_init_spec.rb
spec/zabbixapi/basic/basic_init_spec.rb
require 'spec_helper' describe 'ZabbixApi::Basic' do let(:basic_mock) { ZabbixApi::Basic.new(client) } let(:client) { double } describe '.initialize' do subject { basic_mock } it 'sets passed client object as class variable' do expect(subject.instance_variable_get(:@client)).to eq client end end describe '.method_name' do subject { basic_mock.method_name } it 'raises an ApiError with message' do expect { subject }.to raise_error(ZabbixApi::ApiError, "Can't call method_name here") end end describe '.default_options' do subject { basic_mock.default_options } it { is_expected.to be_empty } end describe '.keys' do subject { basic_mock.keys } let(:key) { 'test-key' } let(:expected) { 'test-keys' } before { allow(basic_mock).to receive(:key).and_return(key) } it { is_expected.to eq expected } end describe '.key' do subject { basic_mock.key } let(:key) { 'test-key' } let(:expected) { 'test-keyid' } before { allow(basic_mock).to receive(:method_name).and_return(key) } it { is_expected.to eq expected } end describe '.identify' do subject { basic_mock.identify } it 'raises an ApiError with message' do expect { subject }.to raise_error(ZabbixApi::ApiError, "Can't call identify here") end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/mediatypes_spec.rb
spec/zabbixapi/classes/mediatypes_spec.rb
require 'spec_helper' describe 'ZabbixApi::Mediatypes' do let(:mediatypes_mock) { ZabbixApi::Mediatypes.new(client) } let(:client) { double } describe '.method_name' do subject { mediatypes_mock.method_name } it { is_expected.to eq 'mediatype' } end describe '.identify' do subject { mediatypes_mock.identify } it { is_expected.to eq 'name' } end describe '.default_options' do subject { mediatypes_mock.default_options } let(:result) do { name: '', description: '', type: 0, smtp_server: '', smtp_helo: '', smtp_email: '', exec_path: '', gsm_modem: '', username: '', passwd: '' } end it { is_expected.to eq result } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/usermacros_spec.rb
spec/zabbixapi/classes/usermacros_spec.rb
require 'spec_helper' describe 'ZabbixApi::Usermacros' do let(:usermacros_mock) { ZabbixApi::Usermacros.new(client) } let(:client) { double } describe '.identify' do subject { usermacros_mock.identify } it { is_expected.to eq 'macro' } end describe '.method_name' do subject { usermacros_mock.method_name } it { is_expected.to eq 'usermacro' } end describe '.get_id' do subject { usermacros_mock.get_id(data) } let(:data) { { 'testidentify' => 1 } } let(:symbolized_data) { { testidentify: 1 } } let(:result) { [{ 'hostmacroid' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { 111 } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:key).and_return(key) allow(usermacros_mock).to receive(:identify).and_return(identify) allow(usermacros_mock).to receive(:symbolize_keys).with(data).and_return(symbolized_data) allow(usermacros_mock).to receive(:request).with( symbolized_data, 'usermacro.get', 'hostmacroid' ).and_return(result) end it 'logs the debug message' do expect(usermacros_mock).to receive(:log).with("[DEBUG] Call get_id with parameters: #{data.inspect}") subject end context 'when data has `identify` as a key' do it 'symbolizes the data' do expect(usermacros_mock).to receive(:symbolize_keys).with(data) subject end it 'returns the id from the response' do expect(subject).to eq id end context 'when request response is empty' do let(:result) { [] } it { is_expected.to be_nil } end end context 'when data does not have `identify` as a key' do let(:identify) { 'wrongtestidentify' } it 'symbolizes the data' do expect(usermacros_mock).not_to receive(:symbolize_keys).with(data) expect { subject }.to raise_error(ZabbixApi::ApiError, "#{identify} not supplied in call to get_id") end end end describe '.get_id_global' do subject { usermacros_mock.get_id_global(data) } let(:data) { { 'testidentify' => 1 } } let(:symbolized_data) { { testidentify: 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { 111 } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:key).and_return(key) allow(usermacros_mock).to receive(:identify).and_return(identify) allow(usermacros_mock).to receive(:symbolize_keys).with(data).and_return(symbolized_data) allow(usermacros_mock).to receive(:request).with( symbolized_data, 'usermacro.get', 'globalmacroid' ).and_return(result) end it 'logs the debug message' do expect(usermacros_mock).to receive(:log).with("[DEBUG] Call get_id_global with parameters: #{data.inspect}") subject end context 'when data has `identify` as a key' do it 'symbolizes the data' do expect(usermacros_mock).to receive(:symbolize_keys).with(data) subject end it 'returns the id from the response' do expect(subject).to eq id end context 'when request response is empty' do let(:result) { [] } it { is_expected.to be_nil } end end context 'when data does not have `identify` as a key' do let(:identify) { 'wrongtestidentify' } it 'symbolizes the data' do expect(usermacros_mock).not_to receive(:symbolize_keys).with(data) expect { subject }.to raise_error(ZabbixApi::ApiError, "#{identify} not supplied in call to get_id_global") end end end describe '.get_full_data' do subject { usermacros_mock.get_full_data(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:request).with( data, 'usermacro.get', 'hostmacroid' ).and_return(result) end it 'logs the debug message' do expect(usermacros_mock).to receive(:log).with("[DEBUG] Call get_full_data with parameters: #{data.inspect}") subject end it { is_expected.to eq result } end describe '.get_full_data_global' do subject { usermacros_mock.get_full_data_global(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:request).with( data, 'usermacro.get', 'globalmacroid' ).and_return(result) end it 'logs the debug message' do expect(usermacros_mock).to receive(:log).with("[DEBUG] Call get_full_data_global with parameters: #{data.inspect}") subject end it { is_expected.to eq result } end describe '.create' do subject { usermacros_mock.create(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:request).with( data, 'usermacro.create', 'hostmacroids' ).and_return(result) end it { is_expected.to eq result } end describe '.create_global' do subject { usermacros_mock.create_global(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:request).with( data, 'usermacro.createglobal', 'globalmacroids' ).and_return(result) end it { is_expected.to eq result } end describe '.delete' do subject { usermacros_mock.delete(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:request).with( [data], 'usermacro.delete', 'hostmacroids' ).and_return(result) end it { is_expected.to eq result } end describe '.delete_global' do subject { usermacros_mock.delete_global(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:request).with( [data], 'usermacro.deleteglobal', 'globalmacroids' ).and_return(result) end it { is_expected.to eq result } end describe '.update' do subject { usermacros_mock.update(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:request).with( data, 'usermacro.update', 'hostmacroids' ).and_return(result) end it { is_expected.to eq result } end describe '.update_global' do subject { usermacros_mock.update_global(data) } let(:data) { { 'hostid' => 1 } } let(:result) { [{ 'globalmacroid' => '111', 'testidentify' => 1 }] } before do allow(usermacros_mock).to receive(:request).with( data, 'usermacro.updateglobal', 'globalmacroids' ).and_return(result) end it { is_expected.to eq result } end describe '.get_or_create_global' do subject { usermacros_mock.get_or_create_global(data) } let(:data) { { macro: 'testdesc', hostid: 'hostid' } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { nil } let(:id_through_create) { 222 } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:get_id_global).with( macro: data[:macro], hostid: data[:hostid] ).and_return(id) allow(usermacros_mock).to receive(:create_global).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(usermacros_mock).to receive(:log).with("[DEBUG] Call get_or_create_global with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update' do subject { usermacros_mock.create_or_update(data) } let(:data) { { macro: 'testdesc', hostid: 'hostid' } } let(:update_data) { { macro: 'testdesc', hostid: 'hostid', hostmacroid: hostmacroid } } let(:hostmacroid) { nil } let(:id_through_create) { 222 } let(:id_through_update) { 333 } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:get_id).with( macro: data[:macro], hostid: data[:hostid] ).and_return(hostmacroid) allow(usermacros_mock).to receive(:update).with(update_data).and_return(id_through_update) allow(usermacros_mock).to receive(:create).with(data).and_return(id_through_create) end context 'when ID already exist' do let(:hostmacroid) { 111 } it 'returns the existing ID' do expect(subject).to eq id_through_update end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update_global' do subject { usermacros_mock.create_or_update_global(data) } let(:data) { { macro: 'testdesc', hostid: 'hostid' } } let(:update_data) { { macro: 'testdesc', hostid: 'hostid', globalmacroid: globalmacroid } } let(:globalmacroid) { nil } let(:id_through_create) { 222 } let(:id_through_update) { 333 } before do allow(usermacros_mock).to receive(:log) allow(usermacros_mock).to receive(:get_id_global).with( macro: data[:macro], hostid: data[:hostid] ).and_return(globalmacroid) allow(usermacros_mock).to receive(:update_global).with(update_data).and_return(id_through_update) allow(usermacros_mock).to receive(:create_global).with(data).and_return(id_through_create) end context 'when ID already exist' do let(:globalmacroid) { 111 } it 'returns the existing ID' do expect(subject).to eq id_through_update end end end # Testing this private method through create_global describe '.request' do subject { usermacros_mock.create_global(data) } let(:data) { { macro: 'testdesc', hostid: 'hostid' } } let(:result) { { 'globalmacroids' => ['111'] } } let(:method) { 'usermacro.createglobal' } before do allow(usermacros_mock).to receive(:log) allow(client).to receive(:api_request).with( method: method, params: data ).and_return(result) end context 'when api response is not empty and contains result key' do it 'returns the first hostmacroid ID' do expect(subject).to eq 111 end end context 'when api response is empty' do let(:result) { {} } it { is_expected.to be_nil } end context 'when method contains `.get`' do subject { usermacros_mock.get_full_data_global(data) } let(:method) { 'usermacro.get' } before do allow(usermacros_mock).to receive(:log) allow(client).to receive(:api_request).with( method: method, params: data ).and_return(result) end context 'when result_key contains `global`' do before do allow('globalmacroid').to receive(:include?).with('global').and_return(false) allow(client).to receive(:api_request).with( method: method, params: { globalmacro: true, filter: data } ).and_return(result) end it { is_expected.to eq result } end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/proxies_spec.rb
spec/zabbixapi/classes/proxies_spec.rb
require 'spec_helper' describe 'ZabbixApi::Proxies' do let(:proxies_mock) { ZabbixApi::Proxies.new(client) } let(:client) { double } describe '.method_name' do subject { proxies_mock.method_name } it { is_expected.to eq 'proxy' } end describe '.identify' do subject { proxies_mock.identify } it { is_expected.to eq 'host' } end describe '.delete' do subject { proxies_mock.delete(data) } let(:data) { { testidentify: 222 } } let(:result) { { 'proxyids' => ['1'] } } let(:identify) { 'testidentify' } let(:method_name) { 'testmethod' } before do allow(proxies_mock).to receive(:log) allow(proxies_mock).to receive(:identify).and_return(identify) allow(proxies_mock).to receive(:method_name).and_return(method_name) allow(client).to receive(:api_request).with( method: 'proxy.delete', params: data ).and_return(result) end context 'when result is not empty' do it 'returns the id of first proxy' do expect(subject).to eq 1 end end context 'when result is empty' do let(:result) { [] } it { is_expected.to be_nil } end end describe '.isreadable' do subject { proxies_mock.isreadable(data) } let(:data) { { testidentify: 222 } } let(:result) { true } let(:identify) { 'testidentify' } let(:method_name) { 'testmethod' } before do allow(proxies_mock).to receive(:log) allow(proxies_mock).to receive(:identify).and_return(identify) allow(proxies_mock).to receive(:method_name).and_return(method_name) allow(client).to receive(:api_request).with( method: 'proxy.isreadable', params: data ).and_return(result) end it { is_expected.to be(true).or be(false) } end describe '.iswritable' do subject { proxies_mock.iswritable(data) } let(:data) { { testidentify: 222 } } let(:result) { true } let(:identify) { 'testidentify' } let(:method_name) { 'testmethod' } before do allow(proxies_mock).to receive(:log) allow(proxies_mock).to receive(:identify).and_return(identify) allow(proxies_mock).to receive(:method_name).and_return(method_name) allow(client).to receive(:api_request).with( method: 'proxy.iswritable', params: data ).and_return(result) end it { is_expected.to be(true).or be(false) } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/items_spec.rb
spec/zabbixapi/classes/items_spec.rb
require 'spec_helper' describe 'ZabbixApi::Items' do let(:items_mock) { ZabbixApi::Items.new(client) } let(:client) { double } describe '.method_name' do subject { items_mock.method_name } it { is_expected.to eq 'item' } end describe '.identify' do subject { items_mock.identify } it { is_expected.to eq 'name' } end describe '.default_options' do subject { items_mock.default_options } let(:result) do { name: nil, key_: nil, hostid: nil, delay: 60, history: 3600, status: 0, type: 7, snmp_community: '', snmp_oid: '', value_type: 3, data_type: 0, trapper_hosts: 'localhost', snmp_port: 161, units: '', multiplier: 0, delta: 0, snmpv3_securityname: '', snmpv3_securitylevel: 0, snmpv3_authpassphrase: '', snmpv3_privpassphrase: '', formula: 0, trends: 86400, logtimefmt: '', valuemapid: 0, delay_flex: '', authtype: 0, username: '', password: '', publickey: '', privatekey: '', params: '', ipmi_sensor: '' } end it { is_expected.to eq result } end describe '.get_or_create' do subject { items_mock.get_or_create(data) } let(:data) { { name: 'batman', hostid: 1234 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(items_mock).to receive(:log) allow(items_mock).to receive(:get_id).with(name: data[:name], hostid: data[:hostid]).and_return(id) allow(items_mock).to receive(:create).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(items_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update' do subject { items_mock.create_or_update(data) } let(:data) { { name: 'batman', hostid: '1234' } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:itemid) { nil } let(:id_through_create) { 222 } let(:update_data) { { name: data[:name], hostid: data[:hostid], itemid: itemid } } before do allow(items_mock).to receive(:log) allow(items_mock).to receive(:identify).and_return(identify) allow(items_mock).to receive(:get_id) .with(name: data[:name], hostid: data[:hostid]).and_return(itemid) allow(items_mock).to receive(:create).with(data).and_return(id_through_create) allow(items_mock).to receive(:update).with(update_data).and_return(itemid) end context 'when Item ID already exist' do let(:itemid) { 1234 } it 'updates an object returns the Item ID' do expect(subject).to eq itemid end end context 'when Item ID does not exist' do it 'creates an object returns the newly created object ID' do expect(subject).to eq id_through_create end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/hosts_spec.rb
spec/zabbixapi/classes/hosts_spec.rb
require 'spec_helper' describe 'ZabbixApi::Hosts' do let(:hosts_mock) { ZabbixApi::Hosts.new(client) } let(:client) { double } describe '.method_name' do subject { hosts_mock.method_name } it { is_expected.to eq 'host' } end describe '.identify' do subject { hosts_mock.identify } it { is_expected.to eq 'host' } end describe '.dump_by_id' do subject { hosts_mock.dump_by_id(data) } let(:data) { { testkey: 222 } } let(:result) { { test: 1 } } let(:key) { 'testkey' } before do allow(hosts_mock).to receive(:log) allow(hosts_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: 'host.get', params: { filter: { testkey: 222 }, output: 'extend', selectGroups: 'shorten' } ).and_return(result) end it 'logs debug message' do expect(hosts_mock).to receive(:log).with("[DEBUG] Call dump_by_id with parameters: #{data.inspect}") subject end it { is_expected.to eq result } end describe '.default_options' do subject { hosts_mock.default_options } let(:result) do { host: nil, interfaces: [], status: 0, available: 1, groups: [], proxy_hostid: nil } end it { is_expected.to eq result } end describe '.unlink_templates' do subject { hosts_mock.unlink_templates(data) } let(:data) { { hosts_id: 222, templates_id: 333 } } let(:result) { { test: 1 } } let(:key) { 'testkey' } before do allow(hosts_mock).to receive(:log) allow(hosts_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: 'host.massRemove', params: { hostids: data[:hosts_id], templates: data[:templates_id] } ).and_return(result) end context 'when result is an empty hash' do let(:result) { {} } it { is_expected.to be_falsy } end context 'when result is not an empty hash' do it { is_expected.to be_truthy } end end describe '.create_or_update' do subject { hosts_mock.create_or_update(data) } let(:data) { { host: 'batman' } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { nil } let(:id_through_create) { 222 } let(:update_data) { { host: 'batman', hostid: 1234 } } before do allow(hosts_mock).to receive(:log) allow(hosts_mock).to receive(:identify).and_return(identify) allow(hosts_mock).to receive(:get_id) .with(host: data[:host]).and_return(id) allow(hosts_mock).to receive(:create).with(data).and_return(id_through_create) allow(hosts_mock).to receive(:update).with(update_data).and_return(id) end context 'when Host ID already exist' do let(:id) { 1234 } it 'updates an object returns the Host ID' do expect(subject).to eq id end end context 'when Host ID does not exist' do it 'creates an object returns the newly created object ID' do expect(subject).to eq id_through_create end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/triggers_spec.rb
spec/zabbixapi/classes/triggers_spec.rb
require 'spec_helper' describe 'ZabbixApi::Triggers' do let(:triggers_mock) { ZabbixApi::Triggers.new(client) } let(:client) { double } describe '.method_name' do subject { triggers_mock.method_name } it { is_expected.to eq 'trigger' } end describe '.identify' do subject { triggers_mock.identify } it { is_expected.to eq 'description' } end describe '.dump_by_id' do subject { triggers_mock.dump_by_id(data) } let(:data) { { testkey: 222 } } let(:result) { { test: 1 } } let(:key) { 'testkey' } before do allow(triggers_mock).to receive(:log) allow(triggers_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: 'trigger.get', params: { filter: { key.to_sym => data[key.to_sym] }, output: 'extend', select_items: 'extend', select_functions: 'extend' } ).and_return(result) end it 'logs debug message' do expect(triggers_mock).to receive(:log).with("[DEBUG] Call dump_by_id with parameters: #{data.inspect}") subject end it { is_expected.to eq result } end describe '.safe_update' do subject { triggers_mock.safe_update(data) } let(:data) { { test: '1', triggerid: 7878, templateid: 4646, expression: '{11a:{22:.33(44)}' } } let(:id_hash) { [{ 'test' => 1 }, { 'test2' => 2 }] } let(:dump) do { test: '1', triggerid: 7878, items: [{ key_: '' }], functions: [{ function: '33', parameter: '44' }], expression: '{11}' } end let(:hash_equals) { true } let(:operation_name) { 'update' } let(:key) { 'test' } let(:result) { 'rtest' } let(:newly_created_item_id) { 1212 } let(:method_name) { 'test_method_name' } let(:data_to_create) do { test: '1', expression: '{11a:{22:.33(44)}' } end before do allow(triggers_mock).to receive(:dump_by_id).with(test: '1').and_return(id_hash) allow(triggers_mock).to receive(:symbolize_keys).with('test' => 1).and_return(dump) allow(triggers_mock).to receive(:hash_equals?).with(dump, data).and_return(hash_equals) allow(triggers_mock).to receive(:key).and_return(key) allow(triggers_mock).to receive(:method_name).and_return(method_name) allow(triggers_mock).to receive(:log) allow(triggers_mock).to receive(:create).with(data_to_create).and_return(newly_created_item_id) allow(client).to receive(:api_request).with( method: "#{method_name}.update", params: [ { triggerid: data[:triggerid], status: '1' } ] ).and_return(result) end it 'logs debug message' do expect(triggers_mock).to receive(:log).with("[DEBUG] Call safe_update with parameters: #{data.inspect}") subject end context 'when dump and data hash are equal' do it 'logs debug message' do expect(triggers_mock).to receive(:log).with('[DEBUG] Equal keys {:test=>"1", :triggerid=>7878, :expression=>"{.33(44)}"} and {:test=>"1", :triggerid=>7878, :expression=>"{.33(44)}"}, skip safe_update') expect(triggers_mock).not_to receive(:log).with("[DEBUG] disable : #{result.inspect}") subject end it 'returns item_id' do expect(subject).to eq 1 end end context 'when dump and data hash are not equal' do let(:hash_equals) { false } it 'logs debug message' do expect(triggers_mock).not_to receive(:log).with(/[DEBUG] Equal keys/) expect(triggers_mock).to receive(:log).with('[DEBUG] disable :"rtest"') subject end it 'returns newly created item_id' do expect(subject).to eq newly_created_item_id end end end describe '.get_or_create' do subject { triggers_mock.get_or_create(data) } let(:data) { { description: 'testdesc', hostid: 'hostid' } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { nil } let(:id_through_create) { 222 } before do allow(triggers_mock).to receive(:log) allow(triggers_mock).to receive(:get_id).with( description: data[:description], hostid: data[:hostid] ).and_return(id) allow(triggers_mock).to receive(:create).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(triggers_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update' do subject { triggers_mock.create_or_update(data) } let(:data) { { description: 'testdesc', hostid: 'hostid' } } before do allow(triggers_mock).to receive(:log) allow(triggers_mock).to receive(:get_or_create) end it 'logs debug message' do expect(triggers_mock).to receive(:log).with("[DEBUG] Call create_or_update with parameters: #{data.inspect}") subject end it 'calls get_or_create function' do expect(triggers_mock).to receive(:get_or_create).with(data) subject end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/graphs_spec.rb
spec/zabbixapi/classes/graphs_spec.rb
require 'spec_helper' describe 'ZabbixApi::Graphs' do let(:graphs_mock) { ZabbixApi::Graphs.new(client) } let(:client) { double } describe '.method_name' do subject { graphs_mock.method_name } it { is_expected.to eq 'graph' } end describe '.identify' do subject { graphs_mock.identify } it { is_expected.to eq 'name' } end describe '.get_full_data' do subject { graphs_mock.get_full_data(data) } let(:data) { { testid: 222 } } let(:result) { { test: 1 } } let(:identify) { 'testid' } let(:method_name) { 'testmethod' } before do allow(graphs_mock).to receive(:log) allow(graphs_mock).to receive(:identify).and_return(identify) allow(graphs_mock).to receive(:method_name).and_return(method_name) allow(client).to receive(:api_request).with( method: "#{method_name}.get", params: { search: { testid: 222 }, output: 'extend' } ).and_return(result) end it 'logs debug message' do expect(graphs_mock).to receive(:log).with("[DEBUG] Call get_full_data with parameters: #{data.inspect}") subject end it { is_expected.to eq result } end describe '.get_ids_by_host' do subject { graphs_mock.get_ids_by_host(data) } let(:data) { { host: 'testhost', filter: 'id3' } } let(:result) do [ { 'graphid' => 1, 'name' => 'testid1' }, { 'graphid' => 2, 'name' => 'testid2', filter: 'id' }, { 'graphid' => 3, 'name' => 'testid3' } ] end let(:ids) { [3] } let(:method_name) { 'testmethod' } before do allow(graphs_mock).to receive(:log) allow(client).to receive(:api_request).with( method: 'graph.get', params: { filter: { host: 'testhost' }, output: 'extend' } ).and_return(result) end context 'when filter is not nil or filter contains name' do it 'returns ids of filter matching graph' do expect(subject).to eq ids end end context 'when filter is nil' do let(:data) { { host: 'testhost' } } let(:ids) { [1, 2, 3] } it 'returns all the ids' do expect(subject).to eq ids end end context 'when filter is not nil or filter does not contain name' do let(:data) { { host: 'testhost', filter: 'wrong' } } let(:ids) { [] } it 'returns an empty array' do expect(subject).to be_empty end end end describe '.get_items' do subject { graphs_mock.get_items(data) } let(:data) { { testid: 222 } } let(:result) { { test: 1 } } let(:identify) { 'testid' } let(:method_name) { 'testmethod' } before do allow(client).to receive(:api_request).with( method: 'graphitem.get', params: { graphids: [data], output: 'extend' } ).and_return(result) end it { is_expected.to eq result } end describe '.get_or_create' do subject { graphs_mock.get_or_create(data) } let(:data) { { name: 'batman', templateid: 1234 } } let(:result) { [{ 'testkey' => '111', 'testid' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(graphs_mock).to receive(:log) allow(graphs_mock).to receive(:get_id).with(name: data[:name], templateid: data[:templateid]).and_return(id) allow(graphs_mock).to receive(:create).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(graphs_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update' do subject { graphs_mock.create_or_update(data) } let(:data) { { name: 'batman', templateid: 1234 } } let(:result) { [{ 'testkey' => '111', 'testid' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testid' } let(:id) { nil } let(:id_through_create) { 222 } let(:update_data) { { name: 'batman', templateid: 1234, graphid: id } } before do allow(graphs_mock).to receive(:log) allow(graphs_mock).to receive(:identify).and_return(identify) allow(graphs_mock).to receive(:get_id) .with(name: data[:name], templateid: data[:templateid]).and_return(id) allow(graphs_mock).to receive(:create).with(data).and_return(id_through_create) allow(graphs_mock).to receive(:_update).with(update_data).and_return(id) end context 'when Graph ID already exist' do let(:id) { '111' } it 'updates an object returns the Graph ID' do expect(subject).to eq id end end context 'when Graph ID does not exist' do it 'creates an object returns the newly created object ID' do expect(subject).to eq id_through_create end end end describe '._update' do subject { graphs_mock._update(data) } let(:data) { { name: 'batman', templateid: 1234 } } let(:id) { '111' } before do allow(graphs_mock).to receive(:update).with(templateid: 1234).and_return(id) end it 'updates an object returns the Graph ID' do expect(subject).to eq id end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/maintenance_spec.rb
spec/zabbixapi/classes/maintenance_spec.rb
require 'spec_helper' describe 'ZabbixApi::Maintenance' do let(:maintenance_mock) { ZabbixApi::Maintenance.new(client) } let(:client) { double } describe '.method_name' do subject { maintenance_mock.method_name } it { is_expected.to eq 'maintenance' } end describe '.identify' do subject { maintenance_mock.identify } it { is_expected.to eq 'name' } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/templates_spec.rb
spec/zabbixapi/classes/templates_spec.rb
require 'spec_helper' describe 'ZabbixApi::Templates' do let(:templates_mock) { ZabbixApi::Templates.new(client) } let(:client) { double } describe '.method_name' do subject { templates_mock.method_name } it { is_expected.to eq 'template' } end describe '.identify' do subject { templates_mock.identify } it { is_expected.to eq 'host' } end describe '.delete' do subject { templates_mock.delete(data) } let(:data) { { testidentify: 222 } } let(:result) { { 'templateids' => ['1'] } } let(:identify) { 'testidentify' } let(:method_name) { 'testmethod' } before do allow(templates_mock).to receive(:log) allow(templates_mock).to receive(:identify).and_return(identify) allow(templates_mock).to receive(:method_name).and_return(method_name) allow(client).to receive(:api_request).with( method: 'template.delete', params: [data] ).and_return(result) end context 'when result is not empty' do it 'returns the id of first template' do expect(subject).to eq 1 end end context 'when result is empty' do let(:result) { [] } it { is_expected.to be_nil } end end describe '.get_ids_by_host' do subject { templates_mock.get_ids_by_host(data) } let(:data) { { scriptid: 222, hostid: 333 } } let(:result) { [{ 'templateid' => 1 }, { 'templateid' => 2 }] } let(:ids) { [1, 2] } before do allow(client).to receive(:api_request).with( method: 'template.get', params: data ).and_return(result) end it { is_expected.to eq ids } end describe '.get_or_create' do subject { templates_mock.get_or_create(data) } let(:data) { { host: 1234 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(templates_mock).to receive(:get_id).with(host: data[:host]).and_return(id) allow(templates_mock).to receive(:create).with(data).and_return(id_through_create) end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.mass_update' do subject { templates_mock.mass_update(data) } let(:data) { { hosts_id: [1234, 5678], templates_id: [1111, 2222] } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(client).to receive(:api_request).with( method: 'template.massUpdate', params: { hosts: [{ hostid: 1234 }, { hostid: 5678 }], templates: [{ templateid: 1111 }, { templateid: 2222 }] } ).and_return(result) end context 'when api_request returns empty result' do let(:result) { [] } it { is_expected.to be_falsy } end context 'when api_request doesn not return empty result' do it { is_expected.to be_truthy } end end describe '.mass_add' do subject { templates_mock.mass_add(data) } let(:data) { { hosts_id: [1234, 5678], templates_id: [1111, 2222] } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(client).to receive(:api_request).with( method: 'template.massAdd', params: { hosts: [{ hostid: 1234 }, { hostid: 5678 }], templates: [{ templateid: 1111 }, { templateid: 2222 }] } ).and_return(result) end context 'when api_request returns empty result' do let(:result) { [] } it { is_expected.to be_falsy } end context 'when api_request doesn not return empty result' do it { is_expected.to be_truthy } end end describe '.mass_remove' do subject { templates_mock.mass_remove(data) } let(:data) { { hosts_id: [1234, 5678], templates_id: [1111, 2222], group_id: 4545 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(client).to receive(:api_request).with( method: 'template.massRemove', params: { hostids: data[:hosts_id], templateids: data[:templates_id], groupids: data[:group_id], force: 1 } ).and_return(result) end context 'when api_request returns empty result' do let(:result) { [] } it { is_expected.to be_falsy } end context 'when api_request doesn not return empty result' do it { is_expected.to be_truthy } end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/actions_spec.rb
spec/zabbixapi/classes/actions_spec.rb
require 'spec_helper' describe 'ZabbixApi::Actions' do let(:actions_mock) { ZabbixApi::Actions.new(client) } let(:client) { double } describe '.method_name' do subject { actions_mock.method_name } it { is_expected.to eq 'action' } end describe '.identify' do subject { actions_mock.identify } it { is_expected.to eq 'name' } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/screens_spec.rb
spec/zabbixapi/classes/screens_spec.rb
require 'spec_helper' describe 'ZabbixApi::Screens' do let(:screens_mock) { ZabbixApi::Screens.new(client) } let(:client) { double } describe '.method_name' do subject { screens_mock.method_name } it { is_expected.to eq 'screen' } end describe '.identify' do subject { screens_mock.identify } it { is_expected.to eq 'name' } end describe '.delete' do subject { screens_mock.delete(data) } let(:data) { { testidentify: 222 } } let(:result) { { 'screenids' => ['1'] } } let(:identify) { 'testidentify' } let(:method_name) { 'testmethod' } before do allow(screens_mock).to receive(:log) allow(screens_mock).to receive(:identify).and_return(identify) allow(screens_mock).to receive(:method_name).and_return(method_name) allow(client).to receive(:api_request).with( method: 'screen.delete', params: [data] ).and_return(result) end context 'when result is not empty' do it 'returns the id of first screen' do expect(subject).to eq 1 end end context 'when result is empty' do let(:result) { [] } it { is_expected.to be_nil } end end describe '.get_or_create_for_host' do subject { screens_mock.get_or_create_for_host(data) } let(:data) { { screen_name: screen_name, graphids: graphids } } let(:screen_name) { 'testscreen' } let(:result) { { 'screenids' => ['1'] } } let(:graphids) { [2222] } let(:method_name) { 'testmethod' } let(:existing_screen_id) { 1212 } let(:newly_created_screen_id) { 3434 } before do allow(screens_mock).to receive(:get_id).with(name: screen_name).and_return(existing_screen_id) end context 'when screen already exist' do it 'returns the id of first screen' do expect(subject).to eq existing_screen_id end end context "when screen doesn't exist" do let(:existing_screen_id) { nil } let(:index) { 0 } let(:screenitems) do [ { resourcetype: 0, resourceid: 2222, x: (index % hsize).to_i, y: (index % graphids.size / hsize).to_i, valign: valign, halign: halign, rowspan: rowspan, colspan: colspan, height: height, width: width } ] end before do allow(screens_mock).to receive(:create).with( name: screen_name, hsize: hsize, vsize: vsize, screenitems: screenitems ).and_return(newly_created_screen_id) end context 'when data do not have all value for request' do let(:hsize) { 3 } let(:valign) { 2 } let(:halign) { 2 } let(:rowspan) { 1 } let(:colspan) { 1 } let(:height) { 320 } let(:width) { 200 } let(:vsize) { [1, (graphids.size / hsize).to_i].max } it 'creates screen with default and rest of provided values' do expect(subject).to eq newly_created_screen_id end end context 'when data do not have all value for request' do let(:hsize) { 3 } let(:valign) { 2 } let(:halign) { 2 } let(:rowspan) { 1 } let(:colspan) { 1 } let(:height) { 320 } let(:width) { 200 } let(:vsize) { 5 } let(:data) do { screen_name: screen_name, graphids: graphids, hsize: hsize, valign: valign, halign: halign, rowspan: rowspan, colspan: colspan, height: height, width: width, vsize: vsize } end it 'creates screen with values provided in data' do expect(subject).to eq newly_created_screen_id end end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/users_spec.rb
spec/zabbixapi/classes/users_spec.rb
require 'spec_helper' describe 'ZabbixApi::Users' do let(:users_mock) { ZabbixApi::Users.new(client) } let(:client) { double } describe '.method_name' do subject { users_mock.method_name } it { is_expected.to eq 'user' } end describe '.identify' do subject { users_mock.identify } it { is_expected.to eq 'alias' } end describe '.key' do subject { users_mock.key } it { is_expected.to eq 'userid' } end describe '.keys' do subject { users_mock.keys } it { is_expected.to eq 'userids' } end describe '.medias_helper' do subject { users_mock.medias_helper(data, action) } let(:data) { { userids: [1234, 5678], media: 'testmedia'} } #let(:result) { { 'mediaids' => ['111'], 'testidentify' => 1 } } let(:result) { { 'userids' => ['111'] } } let(:action) { 'updateMedia' } before do users = data[:userids].map do |t| { userid: t, user_medias: data[:media], } end allow(client).to receive(:api_request).with( method: "user.#{action}", params: users ).and_return(result) end context 'when api_request returns nil result' do let(:result) { nil } it { is_expected.to be_nil } end context 'when api_request does not return empty result' do it 'returns first mediaid' do expect(subject).to eq 111 end end end describe '.add_medias' do subject { users_mock.add_medias(data) } let(:data) { { userids: [1234, 5678], media: 'testmedia' } } let(:result) { { 'userids' => ['111'], 'testidentify' => 1 } } before do allow(users_mock).to receive(:medias_helper) end it 'calls medias_helper' do expect(users_mock).to receive(:medias_helper).with( data, 'update' ) subject end end describe '.update_medias' do subject { users_mock.update_medias(data) } let(:data) { { userids: [1234, 5678], media: 'testmedia' } } let(:result) { { 'userids' => ['111'], 'testidentify' => 1 } } before do allow(users_mock).to receive(:medias_helper) end it 'calls medias_helper' do expect(users_mock).to receive(:medias_helper).with( data, 'update' ) subject end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/httptests_spec.rb
spec/zabbixapi/classes/httptests_spec.rb
require 'spec_helper' describe 'ZabbixApi::HttpTests' do let(:httptests_mock) { ZabbixApi::HttpTests.new(client) } let(:client) { double } describe '.method_name' do subject { httptests_mock.method_name } it { is_expected.to eq 'httptest' } end describe '.identify' do subject { httptests_mock.identify } it { is_expected.to eq 'name' } end describe '.default_options' do subject { httptests_mock.default_options } let(:result) do { hostid: nil, name: nil, steps: [] } end it { is_expected.to eq result } end describe '.get_or_create' do subject { httptests_mock.get_or_create(data) } let(:data) { { name: 'batman', hostid: 1234 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:id) { nil } let(:id_through_create) { 222 } before do allow(httptests_mock).to receive(:log) allow(httptests_mock).to receive(:get_id).with(name: data[:name], hostid: data[:hostid]).and_return(id) allow(httptests_mock).to receive(:create).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(httptests_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update' do subject { httptests_mock.create_or_update(data) } let(:data) { { name: 'batman', hostid: 111 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:httptestid) { nil } let(:id_through_create) { 222 } let(:update_data) { { name: data[:name], hostid: data[:hostid], httptestid: httptestid } } before do allow(httptests_mock).to receive(:log) allow(httptests_mock).to receive(:identify).and_return(identify) allow(httptests_mock).to receive(:get_id) .with(name: data[:name], hostid: data[:hostid]).and_return(httptestid) allow(httptests_mock).to receive(:create).with(data).and_return(id_through_create) allow(httptests_mock).to receive(:update).with(update_data).and_return(httptestid) end context 'when Host ID already exist' do let(:httptestid) { 1234 } it 'updates an object returns the Host ID' do expect(subject).to eq httptestid end end context 'when Host ID does not exist' do it 'creates an object returns the newly created object ID' do expect(subject).to eq id_through_create end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/scripts_spec.rb
spec/zabbixapi/classes/scripts_spec.rb
require 'spec_helper' describe 'ZabbixApi::Scripts' do let(:scripts_mock) { ZabbixApi::Scripts.new(client) } let(:client) { double } describe '.method_name' do subject { scripts_mock.method_name } it { is_expected.to eq 'script' } end describe '.identify' do subject { scripts_mock.identify } it { is_expected.to eq 'name' } end describe '.execute' do subject { scripts_mock.execute(data) } let(:data) { { scriptid: 222, hostid: 333 } } let(:result) { 'testresult' } before do allow(client).to receive(:api_request).with( method: 'script.execute', params: { scriptid: 222, hostid: 333 } ).and_return(result) end it { is_expected.to eq result } end describe '.getscriptsbyhost' do subject { scripts_mock.getscriptsbyhost(data) } let(:data) { { scriptid: 222, hostid: 333 } } let(:result) { 'testresult' } before do allow(client).to receive(:api_request).with( method: 'script.getscriptsbyhosts', params: data ).and_return(result) end it { is_expected.to eq result } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/server_spec.rb
spec/zabbixapi/classes/server_spec.rb
require 'spec_helper' describe 'ZabbixApi::Server' do let(:server_mock) { ZabbixApi::Server.new(client) } let(:client) { double('mock_client', api_version: 'testresult') } let(:result) { 'testresult' } before do allow(client).to receive(:api_request).with( method: 'apiinfo.version', params: {} ).and_return(result) end describe '.initialize' do subject { server_mock } it 'sets client class variable' do expect(subject.instance_variable_get(:@client)).to eq client end it 'sets api_version class variable' do expect(subject.instance_variable_get(:@version)).to eq result end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/valuemap_spec.rb
spec/zabbixapi/classes/valuemap_spec.rb
require 'spec_helper' describe 'ZabbixApi::ValueMaps' do let(:valuemaps_mock) { ZabbixApi::ValueMaps.new(client) } let(:client) { double } describe '.method_name' do subject { valuemaps_mock.method_name } it { is_expected.to eq 'valuemap' } end describe '.identify' do subject { valuemaps_mock.identify } it { is_expected.to eq 'name' } end describe '.key' do subject { valuemaps_mock.key } it { is_expected.to eq 'valuemapid' } end describe '.get_or_create' do subject { valuemaps_mock.get_or_create(data) } let(:data) { { valuemapids: %w[100 101 102 104] } } before do allow(valuemaps_mock).to receive(:log) allow(valuemaps_mock).to receive(:get_id).and_return(data[:valuemapids].first) end it 'logs debug message' do expect(valuemaps_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when id is found' do it 'returns the id' do expect(subject).to eq data[:valuemapids].first end end context 'when id is not found' do before { allow(valuemaps_mock).to receive(:get_id) } it 'creates a new id' do expect(valuemaps_mock).to receive(:create).with(data) subject end end end describe '.create_or_update' do subject { valuemaps_mock.create_or_update(data) } let(:data) { { name: 'fake_valuemap_name' } } let(:id) { 123 } before { allow(valuemaps_mock).to receive(:get_id).with(name: data[:name]).and_return(id) } after { subject } context 'when id is found' do let(:update_data) { data.merge(valuemapids: [id]) } before do allow(data).to receive(:merge).with(valuemapids: [:valuemapid]).and_return(update_data) allow(valuemaps_mock).to receive(:update) end it 'updates the data valueid item' do expect(valuemaps_mock).to receive(:update).with(update_data) end end context 'when id is not found' do before do allow(valuemaps_mock).to receive(:get_id).with(name: data[:name]) allow(valuemaps_mock).to receive(:create).with(data) end it 'creates a new valueid item' do expect(valuemaps_mock).to receive(:create).with(data) end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/applications_spec.rb
spec/zabbixapi/classes/applications_spec.rb
require 'spec_helper' describe 'ZabbixApi::Applications' do let(:actions_mock) { ZabbixApi::Applications.new(client) } let(:client) { double } describe '.method_name' do subject { actions_mock.method_name } it { is_expected.to eq 'application' } end describe '.identify' do subject { actions_mock.identify } it { is_expected.to eq 'name' } end describe '.get_or_create' do subject { actions_mock.get_or_create(data) } let(:data) { { name: 'batman', hostid: 1234 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { nil } let(:id_through_create) { 222 } before do allow(actions_mock).to receive(:log) allow(actions_mock).to receive(:identify).and_return(identify) allow(actions_mock).to receive(:get_id).with(name: data[:name], hostid: data[:hostid]).and_return(id) allow(actions_mock).to receive(:create).with(data).and_return(id_through_create) end it 'logs the debug message' do expect(actions_mock).to receive(:log).with("[DEBUG] Call get_or_create with parameters: #{data.inspect}") subject end context 'when ID already exist' do let(:id) { '111' } it 'returns the existing ID' do expect(subject).to eq id end end context 'when id does not exist' do it 'returns the newly created ID' do expect(subject).to eq id_through_create end end end describe '.create_or_update' do subject { actions_mock.create_or_update(data) } let(:data) { { name: 'batman', hostid: 1234 } } let(:result) { [{ 'testkey' => '111', 'testidentify' => 1 }] } let(:key) { 'testkey' } let(:identify) { 'testidentify' } let(:id) { nil } let(:id_through_create) { 222 } let(:update_data) { { name: 'batman', hostid: 1234, applicationid: id } } before do allow(actions_mock).to receive(:log) allow(actions_mock).to receive(:identify).and_return(identify) allow(actions_mock).to receive(:get_id) .with(name: data[:name], hostid: data[:hostid]).and_return(id) allow(actions_mock).to receive(:create).with(data).and_return(id_through_create) allow(actions_mock).to receive(:update).with(update_data).and_return(id) end context 'when Application ID already exist' do let(:id) { '111' } it 'updates an object returns the object ID' do expect(subject).to eq id end end context 'when Application ID does not exist' do it 'creates an object returns the newly created object ID' do expect(subject).to eq id_through_create end end context 'when an API request raise ApiError' do before do allow(actions_mock).to receive(:create).with(data).and_raise(ZabbixApi::ApiError, 'ApiError occured.') end it 'propogates the ApiError raise by an API' do expect { subject }.to raise_error(ZabbixApi::ApiError, 'ApiError occured.') end end context 'when an API request raise HttpError' do before do allow(actions_mock).to receive(:create).with(data).and_raise(ZabbixApi::HttpError, 'HttpError occured.') end it 'propogates the HttpError raise by an API' do expect { subject }.to raise_error(ZabbixApi::HttpError, 'HttpError occured.') end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/problems_spec.rb
spec/zabbixapi/classes/problems_spec.rb
require 'spec_helper' describe 'ZabbixApi::Problems' do let(:problems_mock) { ZabbixApi::Problems.new(client) } let(:client) { double } describe '.method_name' do subject { problems_mock.method_name } it { is_expected.to eq 'problem' } end describe '.identify' do subject { problems_mock.identify } it { is_expected.to eq 'name' } end # Problem object does not have a unique identifier describe '.key' do subject { problems_mock.key } it { is_expected.to eq 'problemid' } end # Problem object does not have a unique identifier describe '.keys' do subject { problems_mock.keys } it { is_expected.to eq 'problemids' } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/usergroups_spec.rb
spec/zabbixapi/classes/usergroups_spec.rb
require 'spec_helper' describe 'ZabbixApi::Usergroups' do let(:usergroups_mock) { ZabbixApi::Usergroups.new(client) } let(:client) { double } describe '.method_name' do subject { usergroups_mock.method_name } it { is_expected.to eq 'usergroup' } end describe '.identify' do subject { usergroups_mock.identify } it { is_expected.to eq 'name' } end describe '.key' do subject { usergroups_mock.key } it { is_expected.to eq 'usrgrpid' } end describe '.permissions' do subject { usergroups_mock.permissions(data) } let(:data) { { permission: permission, usrgrpid: 123, hostgroupids: [4, 5] } } let(:result) { { 'usrgrpids' => [9090] } } let(:key) { 'testkey' } let(:permission) { 3 } before do rights = data[:hostgroupids].map do |t| { id: t, permission: data[:permission], } end user_groups = { rights: rights, usrgrpid: data[:usrgrpid], } nil_rights = data[:hostgroupids].map do |t| { id: t, permission: 2, } end nil_user_group = { rights: nil_rights, usrgrpid: data[:usrgrpid], } allow(usergroups_mock).to receive(:log) allow(usergroups_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: 'usergroup.update', params: user_groups, ).and_return(result) allow(client).to receive(:api_request).with( method: 'usergroup.update', params: nil_user_group, ).and_return(result) end context 'when permission is provided in data' do it 'uses permission provided in data' do expect(client).to receive(:api_request).with( method: 'usergroup.update', params: { usrgrpid: data[:usrgrpid], rights: data[:hostgroupids].map { |t| { permission: permission, id: t } } } ) subject end it 'returns first usrgrpid' do expect(subject).to eq 9090 end end context 'when permission is not provided in data' do let(:data) { { usrgrpid: 123, hostgroupids: [4, 5] } } let(:permission) { 2 } it 'uses permission provided in data' do expect(client).to receive(:api_request).with( method: 'usergroup.update', params: { usrgrpid: data[:usrgrpid], rights: data[:hostgroupids].map { |t| { permission: permission, id: t } } } ) subject end it 'returns first usrgrpid' do expect(subject).to eq 9090 end end context 'when api returns nil result' do let(:result) { nil } it 'returns nil' do expect(subject).to be_nil end end end describe '.add_user' do subject { usergroups_mock.add_user(data) } let(:data) { { userids: [123, 111], usrgrpids: [4, 5] } } let(:result) { { 'usrgrpids' => [9090] } } let(:key) { 'testkey' } let(:permission) { 3 } before do user_groups = data[:usrgrpids].map do |t| { userids: data[:userids], usrgrpid: t, } end allow(usergroups_mock).to receive(:log) allow(usergroups_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: 'usergroup.update', params: user_groups ).and_return(result) end context 'when returns result with usergroups' do it 'returns first usrgrpid' do expect(subject).to eq 9090 end end context 'when api returns nil result' do let(:result) { nil } it 'returns nil' do expect(subject).to be_nil end end end describe '.update_users' do subject { usergroups_mock.update_users(data) } let(:data) { { userids: [123, 111], usrgrpids: [4, 5] } } let(:result) { { 'usrgrpids' => [9090] } } let(:key) { 'testkey' } let(:permission) { 3 } before do user_groups = data[:usrgrpids].map do |t| { userids: data[:userids], usrgrpid: t, } end allow(usergroups_mock).to receive(:log) allow(usergroups_mock).to receive(:key).and_return(key) allow(client).to receive(:api_request).with( method: 'usergroup.update', params: user_groups, ).and_return(result) end context 'when returns result with usergroups' do it 'returns first usrgrpid' do expect(subject).to eq 9090 end end context 'when api returns nil result' do let(:result) { nil } it 'returns nil' do expect(subject).to be_nil end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/configurations_spec.rb
spec/zabbixapi/classes/configurations_spec.rb
require 'spec_helper' describe 'ZabbixApi::Configurations' do let(:configurations_mock) { ZabbixApi::Configurations.new(client) } let(:client) { double } describe '.array_flag' do subject { configurations_mock.array_flag } it { is_expected.to be_truthy } end describe '.method_name' do subject { configurations_mock.method_name } it { is_expected.to eq 'configuration' } end describe '.identify' do subject { configurations_mock.identify } it { is_expected.to eq 'host' } end describe '.export' do subject { configurations_mock.export(data) } let(:data) { { testdata: 222 } } let(:result) { { test: 1 } } before do allow(client).to receive(:api_request).with( method: 'configuration.export', params: data ).and_return(result) end it { is_expected.to eq result } end describe '.import' do subject { configurations_mock.import(data) } let(:data) { { testdata: 222 } } let(:result) { { test: 1 } } before do allow(client).to receive(:api_request).with( method: 'configuration.import', params: data ).and_return(result) end it { is_expected.to eq result } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/roles_spec.rb
spec/zabbixapi/classes/roles_spec.rb
require 'spec_helper' describe 'ZabbixApi::Roles' do let(:roles_mock) { ZabbixApi::Roles.new(client) } let(:client) { double } describe '.method_name' do subject { roles_mock.method_name } it { is_expected.to eq 'role' } end describe '.identify' do subject { roles_mock.identify } it { is_expected.to eq 'name' } end describe '.key' do subject { roles_mock.key } it { is_expected.to eq 'roleid' } end describe '.keys' do subject { roles_mock.keys } it { is_expected.to eq 'roleids' } end # TODO: fix Roles Spec tests # describe '.add_role' do # subject { roles_mock.add_role(data) } # let(:data) { { userids: [123, 111], usrgrpids: [4, 5] } } # let(:result) { { 'usrgrpids' => [9090] } } # let(:key) { 'testkey' } # let(:permission) { 3 } # before do # roles = data[:usrgrpids].map do |t| # { # userids: data[:userids], # usrgrpid: t, # } # end # allow(roles_mock).to receive(:log) # allow(roles_mock).to receive(:key).and_return(key) # allow(client).to receive(:api_request).with( # method: 'usergroup.update', # params: user_groups # ).and_return(result) # end # context 'when returns result with roles' do # it 'returns first roleid' do # expect(subject).to eq 9090 # end # end # context 'when api returns nil result' do # let(:result) { nil } # it 'returns nil' do # expect(subject).to be_nil # end # end # end # describe '.update_roles' do # subject { roles_mock.update_users(data) } # let(:data) { { userids: [123, 111], usrgrpids: [4, 5] } } # let(:result) { { 'roleids' => [9090] } } # let(:key) { 'testkey' } # let(:permission) { 3 } # before do # roles = data[:roleids].map do |t| # { # userids: data[:userids], # usrgrpid: t, # } # end # allow(roles_mock).to receive(:log) # allow(roles_mock).to receive(:key).and_return(key) # allow(client).to receive(:api_request).with( # method: 'usergroup.update', # params: roles, # ).and_return(result) # end # context 'when returns result with roles' do # it 'returns first roleid' do # expect(subject).to eq 9090 # end # end # context 'when api returns nil result' do # let(:result) { nil } # it 'returns nil' do # expect(subject).to be_nil # end # end # end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/errors_spec.rb
spec/zabbixapi/classes/errors_spec.rb
require 'spec_helper' describe 'ZabbixApi::BaseError' do let(:error_mock) { ZabbixApi::BaseError.new(message, response) } let(:message) { 'Test Message' } let(:response) { { 'error' => { 'data' => error_data, 'message' => error_message } } } let(:error_data) { 'Program is borked' } let(:error_message) { 'something has gone wrong' } describe '.initialize' do subject { error_mock } it 'calls super with error message' do expect_any_instance_of(RuntimeError).to receive(:initialize).with(message) subject end context 'when response is passed in' do it 'response class variable should be set' do expect(subject.instance_variable_get(:@response)).to eq response end it 'error class variable should be set' do expect(subject.instance_variable_get(:@error)).to eq response['error'] end it 'error message class variable should be set' do expect(subject.instance_variable_get(:@error_message)).to eq "#{error_message}: #{error_data}" end end context 'when response is not passed in' do let(:response) { nil } it 'should not set response class variable' do expect(subject.instance_variable_get(:@response)).to be_nil end it 'should not set error class variable' do expect(subject.instance_variable_get(:@error)).to be_nil end it 'should not set error message class variable' do expect(subject.instance_variable_get(:@error_message)).to be_nil end end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/hostgroups_spec.rb
spec/zabbixapi/classes/hostgroups_spec.rb
require 'spec_helper' describe 'ZabbixApi::HostGroups' do let(:actions_mock) { ZabbixApi::HostGroups.new(client) } let(:client) { double } describe '.method_name' do subject { actions_mock.method_name } it { is_expected.to eq 'hostgroup' } end describe '.identify' do subject { actions_mock.identify } it { is_expected.to eq 'name' } end describe '.key' do subject { actions_mock.key } it { is_expected.to eq 'groupid' } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/spec/zabbixapi/classes/unusable_spec.rb
spec/zabbixapi/classes/unusable_spec.rb
require 'spec_helper' describe 'ZabbixApi::Triggers' do let(:unusable_mock) { ZabbixApi::Triggers.new(client) } let(:client) { double } describe '.create_or_update' do subject { unusable_mock.create_or_update(data) } let(:data) { { description: 'testdesc', hostid: 'hostid' } } before do allow(unusable_mock).to receive(:log) allow(unusable_mock).to receive(:get_or_create) end it 'logs debug message' do expect(unusable_mock).to receive(:log).with("[DEBUG] Call create_or_update with parameters: #{data.inspect}") end it 'calls get_or_create' do expect(unusable_mock).to receive(:get_or_create).with(data) end after { subject } end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi.rb
lib/zabbixapi.rb
require 'zabbixapi/version' require 'zabbixapi/client' require 'zabbixapi/basic/basic_alias' require 'zabbixapi/basic/basic_func' require 'zabbixapi/basic/basic_init' require 'zabbixapi/basic/basic_logic' require 'zabbixapi/classes/actions' require 'zabbixapi/classes/applications' require 'zabbixapi/classes/configurations' require 'zabbixapi/classes/errors' require 'zabbixapi/classes/events' require 'zabbixapi/classes/graphs' require 'zabbixapi/classes/hostgroups' require 'zabbixapi/classes/hosts' require 'zabbixapi/classes/httptests' require 'zabbixapi/classes/items' require 'zabbixapi/classes/maintenance' require 'zabbixapi/classes/mediatypes' require 'zabbixapi/classes/proxies' require 'zabbixapi/classes/proxygroup' require 'zabbixapi/classes/problems' require 'zabbixapi/classes/roles' require 'zabbixapi/classes/screens' require 'zabbixapi/classes/scripts' require 'zabbixapi/classes/server' require 'zabbixapi/classes/templates' require 'zabbixapi/classes/triggers' require 'zabbixapi/classes/unusable' require 'zabbixapi/classes/usergroups' require 'zabbixapi/classes/usermacros' require 'zabbixapi/classes/users' require 'zabbixapi/classes/valuemaps' require 'zabbixapi/classes/drules' class ZabbixApi # @return [ZabbixApi::Client] attr_reader :client # Initializes a new ZabbixApi object # # @param options [Hash] # @return [ZabbixApi] def self.connect(options = {}) new(options) end # @return [ZabbixApi] def self.current @current ||= ZabbixApi.new end # Executes an API request directly using a custom query # # @param data [Hash] # @return [Hash] def query(data) @client.api_request(method: data[:method], params: data[:params]) end # Invalidate current authentication token # @return [Boolean] def logout @client.logout end # Initializes a new ZabbixApi object # # @param options [Hash] # @return [ZabbixApi::Client] def initialize(options = {}) @client = Client.new(options) end # @return [ZabbixApi::Actions] def actions @actions ||= Actions.new(@client) end # @return [ZabbixApi::Applications] def applications @applications ||= Applications.new(@client) end # @return [ZabbixApi::Configurations] def configurations @configurations ||= Configurations.new(@client) end # @return [ZabbixApi::Events] def events @events ||= Events.new(@client) end # @return [ZabbixApi::Graphs] def graphs @graphs ||= Graphs.new(@client) end # @return [ZabbixApi::HostGroups] def hostgroups @hostgroups ||= HostGroups.new(@client) end # @return [ZabbixApi::Hosts] def hosts @hosts ||= Hosts.new(@client) end # @return [ZabbixApi::HttpTests] def httptests @httptests ||= HttpTests.new(@client) end # @return [ZabbixApi::Items] def items @items ||= Items.new(@client) end # @return [ZabbixApi::Maintenance] def maintenance @maintenance ||= Maintenance.new(@client) end # @return [ZabbixApi::Mediatypes] def mediatypes @mediatypes ||= Mediatypes.new(@client) end # @return [ZabbixApi::Problems] def problems @problems ||= Problems.new(@client) end # @return [ZabbixApi::Proxies] def proxies @proxies ||= Proxies.new(@client) end # @return [ZabbixApi::Proxygroup] def proxygroup @proxygroup ||= Proxygroup.new(@client) end # @return [ZabbixApi::Roles] def roles @roles ||= Roles.new(@client) end # @return [ZabbixApi::Screens] def screens @screens ||= Screens.new(@client) end # @return [ZabbixApi::Scripts] def scripts @scripts ||= Scripts.new(@client) end # @return [ZabbixApi::Server] def server @server ||= Server.new(@client) end # @return [ZabbixApi::Templates] def templates @templates ||= Templates.new(@client) end # @return [ZabbixApi::Triggers] def triggers @triggers ||= Triggers.new(@client) end # @return [ZabbixApi::Usergroups] def usergroups @usergroups ||= Usergroups.new(@client) end # @return [ZabbixApi::Usermacros] def usermacros @usermacros ||= Usermacros.new(@client) end # @return [ZabbixApi::Users] def users @users ||= Users.new(@client) end # @return [ZabbixApi::ValueMaps] def valuemaps @valuemaps ||= ValueMaps.new(@client) end # @return [ZabbixApi::Drules] def drules @drules ||= Drules.new(@client) end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/version.rb
lib/zabbixapi/version.rb
class ZabbixApi VERSION = '6.0.0-alpha4'.freeze end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/client.rb
lib/zabbixapi/client.rb
require 'net/http' require 'json' require 'openssl' class ZabbixApi class Client # @param (see ZabbixApi::Client#initialize) # @return [Hash] attr_reader :options # @return [Integer] def id rand(100_000) end # Returns the API version from the Zabbix Server # # @return [String] def api_version @api_version ||= api_request(method: 'apiinfo.version', params: {}) @api_version end # Log in to the Zabbix Server and generate an auth token using the API # # @return [Hash] def auth api_request( method: 'user.login', params: { username: @options[:user], password: @options[:password] } ) end # ZabbixApi::Basic.log does not like @client.options[:debug] # # @return [boolean] def debug? return ! @options || @options[:debug] end # Log out from the Zabbix Server # # @return [Boolean] # def logout api_request( :method => 'user.logout', :params => [] ) end # Initializes a new Client object # # @param options [Hash] # @option opts [String] :url The url of zabbixapi(example: 'http://localhost/zabbix/api_jsonrpc.php') # @option opts [String] :user # @option opts [String] :password # @option opts [String] :http_user A user for basic auth.(optional) # @option opts [String] :http_password A password for basic auth.(optional) # @option opts [Integer] :timeout Set timeout for requests in seconds.(default: 60) # # @return [ZabbixApi::Client] def initialize(options = {}) @options = options if !ENV['http_proxy'].nil? && options[:no_proxy] != true @proxy_uri = URI.parse(ENV['http_proxy']) @proxy_host = @proxy_uri.host @proxy_port = @proxy_uri.port @proxy_user, @proxy_pass = @proxy_uri.userinfo.split(/:/) if @proxy_uri.userinfo end unless api_version =~ %r{^5.[0|2]\.\d+$} message = "Zabbix API version: #{api_version} is not supported by this version of zabbixapi" if @options[:ignore_version] puts "[WARNING] #{message}" if @options[:debug] else raise ZabbixApi::ApiError.new(message) end end @auth_hash = auth end # Convert message body to JSON string for the Zabbix API # # @param body [Hash] # @return [String] def message_json(body) message = { method: body[:method], params: body[:params], id: id, jsonrpc: '2.0' } message[:auth] = @auth_hash unless body[:method] == 'apiinfo.version' || body[:method] == 'user.login' JSON.generate(message) end # @param body [String] # @return [String] def http_request(body) uri = URI.parse(@options[:url]) # set the time out the default (60) or to what the user passed timeout = @options[:timeout].nil? ? 60 : @options[:timeout] puts "[DEBUG] Timeout for request set to #{timeout} seconds" if @options[:debug] http = if @proxy_uri Net::HTTP.Proxy(@proxy_host, @proxy_port, @proxy_user, @proxy_pass).new(uri.host, uri.port) else Net::HTTP.new(uri.host, uri.port) end if uri.scheme == 'https' http.use_ssl = true http.verify_mode = OpenSSL::SSL::VERIFY_NONE end http.open_timeout = timeout http.read_timeout = timeout request = Net::HTTP::Post.new(uri.request_uri) request.basic_auth @options[:http_user], @options[:http_password] if @options[:http_user] request.add_field('Content-Type', 'application/json-rpc') request.body = body response = http.request(request) raise HttpError.new("HTTP Error: #{response.code} on #{@options[:url]}", response) unless response.code == '200' puts "[DEBUG] Get answer: #{response.body}" if @options[:debug] response.body end # @param body [String] # @return [Hash, String] def _request(body) puts "[DEBUG] Send request: #{body}" if @options[:debug] result = JSON.parse(http_request(body)) raise ApiError.new("Server answer API error\n #{JSON.pretty_unparse(result['error'])}\n on request:\n #{pretty_body(body)}", result) if result['error'] result['result'] end def pretty_body(body) parsed_body = JSON.parse(body) # If password is in body hide it parsed_body['params']['password'] = '***' if parsed_body['params'].is_a?(Hash) && parsed_body['params'].key?('password') JSON.pretty_unparse(parsed_body) end # Execute Zabbix API requests and return response # # @param body [Hash] # @return [Hash, String] def api_request(body) _request message_json(body) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/basic/basic_func.rb
lib/zabbixapi/basic/basic_func.rb
class ZabbixApi class Basic # Log messages to stdout when debugging # # @param message [String] def log(message) puts message.to_s if @client.options[:debug] end # Compare two hashes for equality # # @param first_hash [Hash] # @param second_hash [Hash] # @return [Boolean] def hash_equals?(first_hash, second_hash) normalized_first_hash = normalize_hash(first_hash) normalized_second_hash = normalize_hash(second_hash) hash1 = normalized_first_hash.merge(normalized_second_hash) hash2 = normalized_second_hash.merge(normalized_first_hash) hash1 == hash2 end # Convert all hash/array keys to symbols # # @param object [Array, Hash] # @return [Array, Hash] def symbolize_keys(object) if object.is_a?(Array) object.each_with_index do |val, index| object[index] = symbolize_keys(val) end elsif object.is_a?(Hash) object.keys.each do |key| object[key.to_sym] = symbolize_keys(object.delete(key)) end end object end # Normalize all hash values to strings # # @param hash [Hash] # @return [Hash] def normalize_hash(hash) result = hash.dup result.delete(:hostid) # TODO: remove to logig. TemplateID and HostID has different id result.each do |key, value| result[key] = value.is_a?(Array) ? normalize_array(value) : value.to_s end result end # Normalize all array values to strings # # @param array [Array] # @return [Array] def normalize_array(array) result = [] array.each do |e| if e.is_a?(Array) result.push(normalize_array(e)) elsif e.is_a?(Hash) result.push(normalize_hash(e)) else result.push(e.to_s) end end result end # Parse a data hash for id key or boolean to return # # @param data [Hash] # @return [Integer] The object id if a single object hash is provided with key # @return [Boolean] True/False if multiple class object hash is provided def parse_keys(data) case data when Hash data.empty? ? nil : data[keys][0].to_i when TrueClass true when FalseClass false end end # Merge two hashes into a single new hash # # @param first_hash [Hash] # @param second_hash [Hash] # @return [Hash] def merge_params(first_hash, second_hash) new = first_hash.dup new.merge(second_hash) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/basic/basic_logic.rb
lib/zabbixapi/basic/basic_logic.rb
class ZabbixApi class Basic # Create new Zabbix object using API (with defaults) # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def create(data) log "[DEBUG] Call create with parameters: #{data.inspect}" data_with_default = default_options.empty? ? data : merge_params(default_options, data) data_create = [data_with_default] result = @client.api_request(method: "#{method_name}.create", params: data_create) parse_keys result end # Delete Zabbix object using API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is deleted # @return [Boolean] True/False if multiple objects are deleted def delete(data) log "[DEBUG] Call delete with parameters: #{data.inspect}" data_delete = [data] result = @client.api_request(method: "#{method_name}.delete", params: data_delete) parse_keys result end # Create or update Zabbix object using API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def create_or_update(data) log "[DEBUG] Call create_or_update with parameters: #{data.inspect}" id = get_id(identify.to_sym => data[identify.to_sym]) id ? update(data.merge(key.to_sym => id.to_s)) : create(data) end # Update Zabbix object using API # # @param data [Hash] Should include object's id field name (identify) and id value # @param force [Boolean] Whether to force an object update even if provided data matches Zabbix # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def update(data, force = false) log "[DEBUG] Call update with parameters: #{data.inspect}" dump = {} dump_by_id(key.to_sym => data[key.to_sym]).each do |item| dump = symbolize_keys(item) if item[key].to_i == data[key.to_sym].to_i end if hash_equals?(dump, data) && !force log "[DEBUG] Equal keys #{dump} and #{data}, skip update" data[key.to_sym].to_i else data_update = [data] result = @client.api_request(method: "#{method_name}.update", params: data_update) parse_keys result end end # Get full/extended Zabbix object data from API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" @client.api_request( method: "#{method_name}.get", params: { filter: { identify.to_sym => data[identify.to_sym] }, output: 'extend' } ) end # Get raw Zabbix object data from API # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_raw(data) log "[DEBUG] Call get_raw with parameters: #{data.inspect}" @client.api_request( method: "#{method_name}.get", params: data ) end # Dump Zabbix object data by key from API # # @param data [Hash] Should include desired object's key and value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def dump_by_id(data) log "[DEBUG] Call dump_by_id with parameters: #{data.inspect}" @client.api_request( method: "#{method_name}.get", params: { filter: { key.to_sym => data[key.to_sym] }, output: 'extend' } ) end # Get full/extended Zabbix data for all objects of type/class from API # # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Array<Hash>] Array of matching objects def all result = {} @client.api_request(method: "#{method_name}.get", params: { output: 'extend' }).each do |item| result[item[identify]] = item[key] end result end # Get Zabbix object id from API based on provided data # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call or missing object's id field name (identify). # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_id(data) log "[DEBUG] Call get_id with parameters: #{data.inspect}" # symbolize keys if the user used string keys instead of symbols data = symbolize_keys(data) if data.key?(identify) # raise an error if identify name was not supplied name = data[identify.to_sym] raise ApiError.new("#{identify} not supplied in call to get_id") if name.nil? result = @client.api_request( method: "#{method_name}.get", params: { filter: data, output: [key, identify] } ) id = nil result.each { |item| id = item[key].to_i if item[identify] == data[identify.to_sym] } id end # Get or Create Zabbix object using API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id def get_or_create(data) log "[DEBUG] Call get_or_create with parameters: #{data.inspect}" unless (id = get_id(identify.to_sym => data[identify.to_sym])) id = create(data) end id end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/basic/basic_init.rb
lib/zabbixapi/basic/basic_init.rb
class ZabbixApi class Basic # Initializes a new Basic object with ZabbixApi Client # # @param client [ZabbixApi::Client] # @return [ZabbixApi::Client] def initialize(client) @client = client end # Placeholder for inherited objects to provide object-specific method name # # @raise [ApiError] Basic object does not directly support method_name def method_name raise ApiError.new("Can't call method_name here") end # Placeholder for inherited objects to provide default options # # @return [Hash] def default_options {} end # Returns the object's plural id field name (identify) based on key # # @return [String] def keys key + 's' end # Returns the object's id field name (identify) based on method_name + id # # @return [String] def key method_name + 'id' end # Placeholder for inherited objects to provide object-specific id field name # # @raise [ApiError] Basic object does not directly support identify def identify raise ApiError.new("Can't call identify here") end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/basic/basic_alias.rb
lib/zabbixapi/basic/basic_alias.rb
class ZabbixApi class Basic # Get Zabbix object data from API by id # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get(data) get_full_data(data) end # Add new Zabbix object using API create # # @param data [Hash] # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is created # @return [Boolean] True/False if multiple objects are created def add(data) create(data) end # Destroy Zabbix object using API delete # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] The object id if a single object is deleted # @return [Boolean] True/False if multiple objects are deleted def destroy(data) delete(data) end def method_name; end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/events.rb
lib/zabbixapi/classes/events.rb
class ZabbixApi class Events < Basic # The method name used for interacting with Events via Zabbix API # # @return [String] def method_name 'event' end # The id field name used for identifying specific Event objects via Zabbix API # # @return [String] def identify 'name' end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/users.rb
lib/zabbixapi/classes/users.rb
class ZabbixApi class Users < Basic # The method name used for interacting with Users via Zabbix API # # @return [String] def method_name 'user' end # The keys field name used for User objects via Zabbix API # # @return [String] def keys 'userids' end # The key field name used for User objects via Zabbix API # # @return [String] def key 'userid' end # The id field name used for identifying specific User objects via Zabbix API # # @return [String] def identify 'alias' end def medias_helper(data, action) result = @client.api_request( method: "user.#{action}", params: data[:userids].map do |t| { userid: t, user_medias: data[:media], } end, ) result ? result['userids'][0].to_i : nil end # Add media to users using Zabbix API # # @param data [Hash] Needs to include userids and media to mass add media to users # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (media) def add_medias(data) medias_helper(data, 'update') end # Update media for users using Zabbix API # # @param data [Hash] Needs to include userids and media to mass update media for users # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Integer] Zabbix object id (user) def update_medias(data) medias_helper(data, 'update') end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false
express42/zabbixapi
https://github.com/express42/zabbixapi/blob/d8f23720aaf1bb6928414c91e02f426dac699c30/lib/zabbixapi/classes/actions.rb
lib/zabbixapi/classes/actions.rb
class ZabbixApi class Actions < Basic # The method name used for interacting with Actions via Zabbix API # # @return [String] def method_name 'action' end # The id field name used for identifying specific Action objects via Zabbix API # # @return [String] def identify 'name' end # Get full/extended Action object data from API # # @param data [Hash] Should include object's id field name (identify) and id value # @raise [ApiError] Error returned when there is a problem with the Zabbix API call. # @raise [HttpError] Error raised when HTTP status from Zabbix Server response is not a 200 OK. # @return [Hash] def get_full_data(data) log "[DEBUG] Call get_full_data with parameters: #{data.inspect}" @client.api_request( method: "#{method_name}.get", params: { filter: { identify.to_sym => data[identify.to_sym] }, output: 'extend', selectOperations: "extend", selectRecoveryOperations: "extend", selectAcknowledgeOperations: "extend", selectFilter: "extend", } ) end end end
ruby
MIT
d8f23720aaf1bb6928414c91e02f426dac699c30
2026-01-04T17:47:42.006756Z
false