From 97f862b81349180614e179b7066468fbf5f4d951 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 1 Dec 2026 18:38:13 +0200 Subject: [PATCH 1/5] Refactor!: rewrite the client for 2.0 2.0 replaces the internals of the gem and most of its surface. Every call that changed is listed in the changelog and in UPGRADING.md. The client. Client.new takes keyword arguments, and an unknown option raises. on_behalf_of returns a new client instead of changing the one it is called on, and logger: takes a Logger. The transport. Requests carry a timeout, and a GET is retried with backoff on connection failures, timeouts and the statuses 429, 500, 502, 503 and 504. A write is never repeated. No Faraday exception escapes: every failure is a ZammadAPI::Error with a class per kind, its message names the request that failed, and a response is a ZammadAPI::Response. A raw request reaches any endpoint the gem does not model. Collections. ListBase, ListAll and ListSearch give way to Collection, which walks every page instead of stopping at the first hundred records, and is built up by chaining: search, page, find_each. Records. Dispatcher gives way to ResourceProxy, reached through plural readers such as client.tickets, and a class of the caller's own works through client.resource. save answers false on a validation failure, and save! raises. The toolchain moves with the code: Ruby 3.4, faraday-retry, the RuboCop configuration without its todo file, and a Rakefile that separates the unit specs from the ones that need a live Zammad. The specs under spec/unit are new and need no Zammad. The version is 2.0.0.alpha1. The live specs, which were the whole suite of 1.x, are one file under spec/integration. Each example makes the records it needs and destroys them, and none asserts on what else the instance holds, so the suite passes against the same Zammad as often as it is run. As it creates and deletes records, it runs only against the Zammad that TEST_URL names: there is no default. The Rakefile's steep and rbs_published tasks have nothing to check until the signatures arrive in the next commit. --- .gitignore | 4 +- .overcommit.yml | 50 +- .rspec | 1 + .rubocop.yml | 126 ++-- .rubocop_todo.yml | 35 -- .ruby-version | 1 + Gemfile | 32 +- Gemfile.lock | 113 +++- Rakefile | 61 +- bin/console | 8 + bin/setup | 6 + examples/example_http_token.rb | 59 -- lib/zammad_api.rb | 19 +- lib/zammad_api/attribute_access.rb | 121 ++++ lib/zammad_api/client.rb | 286 +++++++-- lib/zammad_api/collection.rb | 233 +++++++ lib/zammad_api/config.rb | 239 ++++++++ lib/zammad_api/deep_copy.rb | 43 ++ lib/zammad_api/dispatcher.rb | 12 - lib/zammad_api/errors.rb | 132 ++-- lib/zammad_api/json_helper.rb | 11 - lib/zammad_api/list_all.rb | 11 - lib/zammad_api/list_base.rb | 84 --- lib/zammad_api/list_search.rb | 11 - lib/zammad_api/log.rb | 18 - lib/zammad_api/resource_proxy.rb | 195 ++++++ lib/zammad_api/resources.rb | 26 +- lib/zammad_api/resources/base.rb | 289 ++++++--- lib/zammad_api/resources/group.rb | 14 +- lib/zammad_api/resources/organization.rb | 14 +- lib/zammad_api/resources/ticket.rb | 61 +- lib/zammad_api/resources/ticket_article.rb | 21 +- .../resources/ticket_article_attachment.rb | 42 +- lib/zammad_api/resources/ticket_priority.rb | 12 +- lib/zammad_api/resources/ticket_state.rb | 11 +- lib/zammad_api/resources/user.rb | 18 +- lib/zammad_api/response.rb | 52 ++ lib/zammad_api/transport.rb | 252 ++++++-- lib/zammad_api/version.rb | 5 +- spec/integration/zammad_api_spec.rb | 288 +++++++++ spec/spec_helper.rb | 86 +-- spec/support/client_helper.rb | 29 + spec/support/integration_helper.rb | 32 + spec/support/strong_parameters.rb | 14 + spec/unit/zammad_api/attribute_access_spec.rb | 243 ++++++++ spec/unit/zammad_api/client_spec.rb | 437 +++++++++++++ spec/unit/zammad_api/collection_spec.rb | 470 ++++++++++++++ spec/unit/zammad_api/config_spec.rb | 280 +++++++++ spec/unit/zammad_api/resource_proxy_spec.rb | 458 ++++++++++++++ spec/unit/zammad_api/resources/base_spec.rb | 558 +++++++++++++++++ .../ticket_article_attachment_spec.rb | 93 +++ spec/unit/zammad_api/resources/ticket_spec.rb | 119 ++++ spec/unit/zammad_api/response_error_spec.rb | 154 +++++ spec/unit/zammad_api/response_spec.rb | 76 +++ spec/unit/zammad_api/transport_spec.rb | 575 ++++++++++++++++++ spec/zammad_api/client_spec.rb | 110 ---- spec/zammad_api/errors_spec.rb | 164 ----- spec/zammad_api/json_helper_spec.rb | 21 - spec/zammad_api/resources/group_spec.rb | 154 ----- spec/zammad_api/resources/list_base_spec.rb | 7 - .../zammad_api/resources/organization_spec.rb | 215 ------- .../resources/ticket_priority_spec.rb | 135 ---- spec/zammad_api/resources/ticket_spec.rb | 223 ------- .../zammad_api/resources/ticket_state_spec.rb | 185 ------ spec/zammad_api/resources/user_spec.rb | 275 --------- spec/zammad_api/transport_spec.rb | 80 --- spec/zammad_api_spec.rb | 36 -- zammad_api.gemspec | 67 +- 68 files changed, 5982 insertions(+), 2330 deletions(-) delete mode 100644 .rubocop_todo.yml create mode 100644 .ruby-version create mode 100755 bin/console create mode 100755 bin/setup delete mode 100755 examples/example_http_token.rb create mode 100644 lib/zammad_api/attribute_access.rb create mode 100644 lib/zammad_api/collection.rb create mode 100644 lib/zammad_api/config.rb create mode 100644 lib/zammad_api/deep_copy.rb delete mode 100644 lib/zammad_api/dispatcher.rb delete mode 100644 lib/zammad_api/json_helper.rb delete mode 100644 lib/zammad_api/list_all.rb delete mode 100644 lib/zammad_api/list_base.rb delete mode 100644 lib/zammad_api/list_search.rb delete mode 100644 lib/zammad_api/log.rb create mode 100644 lib/zammad_api/resource_proxy.rb create mode 100644 lib/zammad_api/response.rb create mode 100644 spec/integration/zammad_api_spec.rb create mode 100644 spec/support/client_helper.rb create mode 100644 spec/support/integration_helper.rb create mode 100644 spec/support/strong_parameters.rb create mode 100644 spec/unit/zammad_api/attribute_access_spec.rb create mode 100644 spec/unit/zammad_api/client_spec.rb create mode 100644 spec/unit/zammad_api/collection_spec.rb create mode 100644 spec/unit/zammad_api/config_spec.rb create mode 100644 spec/unit/zammad_api/resource_proxy_spec.rb create mode 100644 spec/unit/zammad_api/resources/base_spec.rb create mode 100644 spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb create mode 100644 spec/unit/zammad_api/resources/ticket_spec.rb create mode 100644 spec/unit/zammad_api/response_error_spec.rb create mode 100644 spec/unit/zammad_api/response_spec.rb create mode 100644 spec/unit/zammad_api/transport_spec.rb delete mode 100644 spec/zammad_api/client_spec.rb delete mode 100644 spec/zammad_api/errors_spec.rb delete mode 100644 spec/zammad_api/json_helper_spec.rb delete mode 100644 spec/zammad_api/resources/group_spec.rb delete mode 100644 spec/zammad_api/resources/list_base_spec.rb delete mode 100644 spec/zammad_api/resources/organization_spec.rb delete mode 100644 spec/zammad_api/resources/ticket_priority_spec.rb delete mode 100644 spec/zammad_api/resources/ticket_spec.rb delete mode 100644 spec/zammad_api/resources/ticket_state_spec.rb delete mode 100644 spec/zammad_api/resources/user_spec.rb delete mode 100644 spec/zammad_api/transport_spec.rb delete mode 100644 spec/zammad_api_spec.rb diff --git a/.gitignore b/.gitignore index 002a2a1a..bb396ef6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,6 @@ /.bundle/ -/.ruby-version -/.yardoc +/.steep/ +/.yardoc/ /_yardoc/ /coverage/ /doc/ diff --git a/.overcommit.yml b/.overcommit.yml index 8553cbeb..740cb168 100644 --- a/.overcommit.yml +++ b/.overcommit.yml @@ -1,33 +1,23 @@ -# Use this file to configure the Overcommit hooks you wish to use. This will -# extend the default configuration defined in: -# https://github.com/sds/overcommit/blob/master/config/default.yml +# See https://github.com/sds/overcommit#configuration # -# At the topmost level of this YAML file is a key representing type of hook -# being run (e.g. pre-commit, commit-msg, etc.). Within each type you can -# customize each hook, such as whether to only run it on certain files (via -# `include`), whether to only display output if it fails (via `quiet`), etc. -# -# For a complete list of hooks, see: -# https://github.com/sds/overcommit/tree/master/lib/overcommit/hook -# -# For a complete list of options that you can use to customize hooks, see: -# https://github.com/sds/overcommit#configuration -# -# Uncomment the following lines to make the configuration take effect. +# Install with: bundle exec overcommit --install PreCommit: - RuboCop: - enabled: true - on_warn: fail # Treat all warnings as failures -# -# TrailingWhitespace: -# enabled: true -# exclude: -# - '**/db/structure.sql' # Ignore trailing whitespace in generated files -# -#PostCheckout: -# ALL: # Special hook name that customizes all hooks of this type -# quiet: true # Change all post-checkout hooks to only display output on failure -# -# IndexTags: -# enabled: true # Generate a tags file with `ctags` each time HEAD changes + RuboCop: + enabled: true + on_warn: fail # Treat all warnings as failures + command: ['bundle', 'exec', 'rubocop'] + + TrailingWhitespace: + enabled: true + + YamlSyntax: + enabled: true + + BundleCheck: + enabled: true + + RSpec: + enabled: true + description: 'Run the unit specs' + command: ['bundle', 'exec', 'rspec', 'spec/unit'] diff --git a/.rspec b/.rspec index 8c18f1ab..7a2cc1a6 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,3 @@ +--require spec_helper --format documentation --color diff --git a/.rubocop.yml b/.rubocop.yml index 0ae18f9a..feca3c31 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,117 +1,67 @@ -# Default enabled cops -# https://github.com/bbatsov/rubocop/blob/master/config/enabled.yml - plugins: - rubocop-performance - rubocop-rake - rubocop-rspec -inherit_from: - - .rubocop_todo.yml - AllCops: NewCops: enable Exclude: - - 'bin/rails' - - 'bin/rake' - - 'bin/spring' - - 'db/schema.rb' - - 'examples/**/*' - # Match the Ruby version specified in the gemspec. - TargetRubyVersion: 3.0 + - 'pkg/**/*' + - 'vendor/**/*' + # Keep in sync with required_ruby_version in the gemspec and the CI matrix. + TargetRubyVersion: 3.4 -# Zammad StyleGuide - -Style/FrozenStringLiteralComment: - Enabled: false +# --- Zammad style guide ----------------------------------------------------- Style/NegatedIf: - Description: >- - Favor unless over if for negative conditions - (or control flow or). - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#unless-for-negatives' + Description: 'Zammad prefers an explicit `if !x` over `unless x`.' Enabled: false Style/IfUnlessModifier: - Description: >- - Favor modifier if/unless usage when you have a - single-line body. - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#if-as-a-modifier' - Enabled: false - -Style/TrailingCommaInArrayLiteral: - Description: 'Checks for trailing comma in array literals.' - StyleGuide: '#no-trailing-array-commas' - Enabled: false - -Style/TrailingCommaInHashLiteral: - Description: 'Checks for trailing comma in hash literals.' - Enabled: false - -Style/TrailingCommaInArguments: - Description: 'Checks for trailing comma in argument lists.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-trailing-array-commas' + Description: 'Zammad allows multi-line bodies for a single condition.' Enabled: false Layout/LeadingCommentSpace: - Description: 'Comments should start with a space.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-space' - Enabled: false + # `#: Type`, the annotation Steep reads. + AllowRBSInlineAnnotation: true Layout/HashAlignment: - Description: >- - Align the elements of a hash literal if they span more than - one line. Enabled: true EnforcedHashRocketStyle: table EnforcedColonStyle: table EnforcedLastArgumentHashStyle: always_inspect -Style/ClassAndModuleChildren: - Description: 'Checks style of children classes and modules.' - Enabled: false - -Naming/MethodParameterName: - Description: >- - Checks for method parameter names that contain capital letters, - end in numbers, or do not meet a minimal length. - Enabled: true - AllowedNames: [id] - Layout/MultilineMethodCallIndentation: - Description: >- - Checks the indentation of the method name part in method calls - that span more than one line. EnforcedStyle: indented Style/RescueStandardError: EnforcedStyle: implicit -Style/Documentation: - Enabled: false +Style/ArgumentsForwarding: + # Named parameters keep public signatures self-documenting for YARD/RBS. + UseAnonymousForwarding: false -Style/PerlBackrefs: - Description: 'Avoid Perl-style regex back references.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#no-perl-regexp-last-matchers' - Enabled: false +Naming/BlockForwarding: + EnforcedStyle: explicit + +Naming/PredicateMethod: + # Established names from the resource API. `save` reports whether the record + # was stored; the rest return true on success. + AllowedMethods: + - save! + - destroy -Style/BlockComments: - # Keep block comments (=begin ... =end) to allow for easy copy-pasting of examples. - Description: 'Do not use block comments.' +Style/Documentation: + Description: 'Public API documentation is enforced by review, not by this cop.' Enabled: false Layout/LineLength: - Description: 'Limit lines to 80 characters.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#80-character-limits' Enabled: false Metrics/ClassLength: - Description: 'Avoid classes longer than 100 lines of code.' Enabled: false Metrics/MethodLength: - Description: 'Avoid methods longer than 10 lines of code.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#short-methods' Enabled: false Metrics/AbcSize: @@ -123,21 +73,17 @@ Metrics/CyclomaticComplexity: Metrics/PerceivedComplexity: Max: 12 +Metrics/ParameterLists: + # Config mirrors every supported option as a keyword argument. + Max: 16 + MaxOptionalParameters: 15 + +# --- Specs ------------------------------------------------------------------ + RSpec/ExampleLength: - inherit_mode: - merge: - - Exclude - CountAsOne: - - 'array' - - 'hash' - - 'heredoc' - Max: 25 - -RSpec/NestedGroups: - Max: 6 - -# Broken!!!! Generates broken code since "String".downcase == "strinG".downcase is not equals "String".casecmp("strinG") but "String".casecmp("strinG") == 0 !!! -Performance/Casecmp: - Description: 'Use `casecmp` rather than `downcase ==`.' - Reference: 'https://github.com/JuanitoFatas/fast-ruby#stringcasecmp-vs-stringdowncase---code' - Enabled: false + CountAsOne: ['array', 'hash', 'heredoc'] + Max: 12 + +RSpec/MultipleExpectations: + Description: 'A few request assertions per example are clearer than splitting them.' + Max: 3 diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index 20ec1c6c..00000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,35 +0,0 @@ -Naming/PredicateMethod: - Enabled: false - -Style/MissingRespondToMissing: - Enabled: false - -Style/StringConcatenation: - Enabled: false - -Naming/AccessorMethodName: - Enabled: false - -RSpec/MultipleExpectations: - Enabled: false - -RSpec/ExampleLength: - Enabled: false - -RSpec/SpecFilePathFormat: - Enabled: false - -RSpec/NoExpectationExample: - Enabled: false - -RSpec/DescribeMethod: - Enabled: false - -RSpec/ContextWording: - Enabled: false - -RSpec/BeforeAfterAll: - Enabled: false - -RSpec/LeakyLocalVariable: - Enabled: false diff --git a/.ruby-version b/.ruby-version new file mode 100644 index 00000000..7919852f --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +4.0.9 diff --git a/Gemfile b/Gemfile index 2d9e06ba..9f99a51c 100644 --- a/Gemfile +++ b/Gemfile @@ -1,17 +1,27 @@ +# frozen_string_literal: true + source 'https://rubygems.org' -# runtime dependencies are defined in zammad_api.gemspec +# Runtime dependencies are defined in zammad_api.gemspec. gemspec -# development dependencies group :development, :test do - gem 'bundler', '>= 2.2.10' - gem 'overcommit' - gem 'rake' - gem 'rspec' - gem 'rubocop' - gem 'rubocop-performance' - gem 'rubocop-rake' - gem 'rubocop-rspec' - gem 'webmock' + gem 'overcommit', require: false + gem 'rake', require: false + gem 'rspec', '~> 3.13' + gem 'rubocop', require: false + gem 'rubocop-performance', require: false + gem 'rubocop-rake', require: false + gem 'rubocop-rspec', require: false + gem 'simplecov', '~> 1.3', require: false + gem 'webmock', '~> 3.26' +end + +group :development do + # For bin/console. A bundled gem from Ruby 4.0 on, which Bundler makes + # loadable only where the bundle names it. + gem 'irb', require: false + # Static type checking against the signatures in sig/. + gem 'rbs', require: false + gem 'steep', require: false end diff --git a/Gemfile.lock b/Gemfile.lock index 18b0d1c8..696361c2 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -1,8 +1,10 @@ PATH remote: . specs: - zammad_api (1.3.1) - faraday (~> 2) + zammad_api (2.0.0.alpha1) + faraday (~> 2.9) + faraday-retry (~> 2.2) + logger (~> 1.5) GEM remote: https://rubygems.org/ @@ -13,21 +15,48 @@ GEM bigdecimal (4.1.3) childprocess (5.1.0) logger (~> 1.5) + concurrent-ruby (1.3.8) crack (1.0.1) bigdecimal rexml + csv (3.3.7) diff-lcs (1.6.2) + erb (6.0.7) faraday (2.15.1) faraday-net_http (>= 2.0, < 3.6) json logger faraday-net_http (3.5.0) net-http (~> 0.5) + faraday-retry (2.4.0) + faraday (~> 2.0) + ffi (1.17.4) + ffi (1.17.4-aarch64-linux-gnu) + ffi (1.17.4-aarch64-linux-musl) + ffi (1.17.4-arm-linux-gnu) + ffi (1.17.4-arm-linux-musl) + ffi (1.17.4-arm64-darwin) + ffi (1.17.4-x86-linux-gnu) + ffi (1.17.4-x86-linux-musl) + ffi (1.17.4-x86_64-darwin) + ffi (1.17.4-x86_64-linux-gnu) + ffi (1.17.4-x86_64-linux-musl) + fileutils (1.8.1) hashdiff (1.3.0) iniparse (1.5.0) + io-console (0.9.5) + irb (1.19.0) + pp (>= 0.6.0) + prism (>= 1.3.0) + rdoc (>= 4.0.0) + reline (>= 0.4.2) json (3.2.0) language_server-protocol (3.17.0.6) lint_roller (1.1.0) + listen (3.10.1) + logger + rb-fsevent (~> 0.10, >= 0.10.3) + rb-inotify (~> 0.9, >= 0.9.10) logger (1.7.0) net-http (0.10.0) net-protocol (>= 0.3.0) @@ -38,30 +67,55 @@ GEM childprocess (>= 5.0.0, < 6) iniparse (~> 1.4) rexml (>= 3.4.2) - parallel (1.28.0) + parallel (2.3.0) parser (3.3.14.0) ast (~> 2.4.1) racc + pp (0.6.4) + prettyprint + prettyprint (0.2.1) prism (2.1.0) - public_suffix (6.0.2) + prism (2.1.0-aarch64-linux-gnu) + prism (2.1.0-aarch64-linux-musl) + prism (2.1.0-arm-linux-gnu) + prism (2.1.0-arm-linux-musl) + prism (2.1.0-arm64-darwin) + prism (2.1.0-x86_64-darwin) + prism (2.1.0-x86_64-linux-gnu) + prism (2.1.0-x86_64-linux-musl) + public_suffix (7.0.5) racc (1.8.1) rainbow (3.1.1) rake (13.4.2) + rb-fsevent (0.11.2) + rb-inotify (0.11.1) + ffi (~> 1.0) + rbs (4.2.0) + logger + prism (>= 1.6.0) + tsort + rdoc (8.1.0) + erb + prism (>= 1.6.0) + rbs (>= 4.0.0) + tsort regexp_parser (2.13.4) + reline (0.7.0) + io-console (~> 0.5) rexml (3.4.4) rspec (3.13.2) rspec-core (~> 3.13.0) rspec-expectations (~> 3.13.0) rspec-mocks (~> 3.13.0) - rspec-core (3.13.6) + rspec-core (3.13.7) rspec-support (~> 3.13.0) - rspec-expectations (3.13.5) + rspec-expectations (3.13.6) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-mocks (3.13.8) + rspec-mocks (3.13.9) diff-lcs (>= 1.2.0, < 2.0) rspec-support (~> 3.13.0) - rspec-support (3.13.7) + rspec-support (3.13.8) rubocop (1.93.0) json (>= 2.3) language_server-protocol (~> 3.17.0.2) @@ -89,7 +143,29 @@ GEM lint_roller (~> 1.1) rubocop (~> 1.92) ruby-progressbar (1.13.0) + securerandom (0.4.1) + simplecov (1.3.2) + steep (2.1.0) + concurrent-ruby (>= 1.1.10) + csv (>= 3.0.9) + fileutils (>= 1.1.0) + json (>= 2.1.0) + language_server-protocol (>= 3.17.0.4, < 4.0) + listen (~> 3.0) + logger (>= 1.3.0) + parser (>= 3.2) + prism (>= 0.25.0) + rainbow (>= 2.2.2, < 4.0) + rbs (~> 4.2) + securerandom (>= 0.1) + strscan (>= 1.0.0) + terminal-table (>= 2, < 5) + uri (>= 0.12.0) + strscan (3.1.8) + terminal-table (4.0.0) + unicode-display_width (>= 1.1.1, < 4) timeout (0.6.1) + tsort (0.2.0) unicode-display_width (3.3.0) unicode-emoji (~> 4.3) unicode-emoji (4.3.0) @@ -100,19 +176,32 @@ GEM hashdiff (>= 0.4.0, < 2.0.0) PLATFORMS + aarch64-linux-gnu + aarch64-linux-musl + arm-linux-gnu + arm-linux-musl + arm64-darwin ruby + x86-linux-gnu + x86-linux-musl + x86_64-darwin + x86_64-linux-gnu + x86_64-linux-musl DEPENDENCIES - bundler (>= 2.2.10) + irb overcommit rake - rspec + rbs + rspec (~> 3.13) rubocop rubocop-performance rubocop-rake rubocop-rspec - webmock + simplecov (~> 1.3) + steep + webmock (~> 3.26) zammad_api! BUNDLED WITH - 2.6.9 + 4.0.20 diff --git a/Rakefile b/Rakefile index 4c774a2b..a229aeb5 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,63 @@ +# frozen_string_literal: true + require 'bundler/gem_tasks' +require 'fileutils' require 'rspec/core/rake_task' +require 'rubocop/rake_task' + +namespace :spec do + desc 'Run the unit specs (no Zammad instance required)' + RSpec::Core::RakeTask.new(:unit) do |task| + task.pattern = 'spec/unit/**/*_spec.rb' + end + + desc 'Run the integration specs against the Zammad that TEST_URL names' + RSpec::Core::RakeTask.new(integration: :live_target) do |task| + task.pattern = 'spec/integration/**/*_spec.rb' + end +end + +desc 'Run all specs' +task spec: [:live_target, 'spec:unit', 'spec:integration'] + +# The integration specs create and delete records, so there is no default for +# where. Asked here as well as in the specs, so that a task which was asked +# to run them says why it did not rather than passing with them left out. +desc 'Check that TEST_URL names the Zammad to run the integration specs against' +task :live_target do + if ENV['TEST_URL'].to_s.strip.empty? + abort 'TEST_URL is not set. The integration specs create and delete records in the Zammad it names, so make ' \ + 'it one you can lose: TEST_URL=https://zammad.example/ TEST_USER=admin@example.com TEST_PASSWORD=test' + end +end + +RuboCop::RakeTask.new + +desc 'Type-check lib/ against the signatures in sig/' +task :steep do + sh 'bundle exec steep check' +end + +# sig/vendor stands in for dependencies that ship no signatures and is kept +# out of the gem, so the published set has to hold up without it. Nothing +# else here notices a published signature that names a Faraday type, because +# sig/vendor is always on the load path in this repository. +desc 'Check that the signatures the gem ships validate without sig/vendor' +task :rbs_published do + require 'tmpdir' -RSpec::Core::RakeTask.new(:spec) + Dir.mktmpdir do |dir| + published = Dir['sig/**/*.rbs'].grep_v(%r{\Asig/vendor/}) + published.each do |file| + target = File.join(dir, file) + FileUtils.mkdir_p(File.dirname(target)) + FileUtils.cp(file, target) + end + # `logger` is the only library the published signatures name, and it is a + # standard one RBS ships declarations for, so a consumer already has it. + sh "bundle exec rbs -r logger -I #{File.join(dir, 'sig')} validate" + end +end -task default: :spec +desc 'Run everything that does not need a Zammad instance' +task default: ['spec:unit', :rubocop, :steep, :rbs_published] diff --git a/bin/console b/bin/console new file mode 100755 index 00000000..dcbd7d12 --- /dev/null +++ b/bin/console @@ -0,0 +1,8 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +require 'bundler/setup' +require 'zammad_api' +require 'irb' + +IRB.start(__FILE__) diff --git a/bin/setup b/bin/setup new file mode 100755 index 00000000..bc8f0ad2 --- /dev/null +++ b/bin/setup @@ -0,0 +1,6 @@ +#!/usr/bin/env bash +set -euo pipefail +IFS=$'\n\t' + +bundle install +bundle exec overcommit --install diff --git a/examples/example_http_token.rb b/examples/example_http_token.rb deleted file mode 100755 index 5cf58033..00000000 --- a/examples/example_http_token.rb +++ /dev/null @@ -1,59 +0,0 @@ -#!/usr/bin/env ruby - -$LOAD_PATH << './lib' -require 'rubygems' -require 'zammad_api' - -client = ZammadAPI::Client.new( - url: 'https://you.zammad.com/', - http_token: 'XXXX', -) - -# create ticket -ticket = client.ticket.new( - title: 'some new title', - state: 'new', - priority: '2 normal', - owner: '-', - customer: 'nicole.braun@zammad.org', - group: 'Users', - article: { - sender: 'Customer', - type: 'note', - subject: 'some subject', - content_type: 'text/plain', - body: "some body\nnext line", - } -) -ticket.save - -p '--------------------------------------------------------' -p "Ticket has been created: #{ticket.number} - #{ticket.title} at #{ticket.created_at}" -p " Attributes: #{ticket.attributes.inspect}" - -# get ticket -p '--------------------------------------------------------' -ticket = client.ticket.find(ticket.id) -p "Ticket found on server: #{ticket.number} - #{ticket.title} at #{ticket.created_at}" -p " Attributes: #{ticket.attributes.inspect}" - -# get articles of ticket -p '--------------------------------------------------------' -articles = ticket.articles -p "Total #{articles.length} articles" - -# create article -p '--------------------------------------------------------' -article = ticket.article( - type: 'note', - subject: 'some subject 2', - body: 'some body 2', -) -p "Article has been created: #{article.subject} at #{article.created_at}" -p " Attributes: #{article.attributes.inspect}" - -# get articles of ticket -p '--------------------------------------------------------' -articles = ticket.articles -p "Total #{articles.length} articles now" -p '--------------------------------------------------------' diff --git a/lib/zammad_api.rb b/lib/zammad_api.rb index 608477d9..7bbba75b 100644 --- a/lib/zammad_api.rb +++ b/lib/zammad_api.rb @@ -1,6 +1,19 @@ -require 'zammad_api/version' -require 'zammad_api/errors' -require 'zammad_api/client' +# frozen_string_literal: true +require_relative 'zammad_api/version' +require_relative 'zammad_api/errors' +require_relative 'zammad_api/deep_copy' +require_relative 'zammad_api/config' +require_relative 'zammad_api/response' +require_relative 'zammad_api/transport' +require_relative 'zammad_api/attribute_access' +require_relative 'zammad_api/collection' +require_relative 'zammad_api/resources' +require_relative 'zammad_api/resource_proxy' +require_relative 'zammad_api/client' + +# Ruby client for the Zammad API v1.0. +# +# @see Client module ZammadAPI end diff --git a/lib/zammad_api/attribute_access.rb b/lib/zammad_api/attribute_access.rb new file mode 100644 index 00000000..aaa86dbd --- /dev/null +++ b/lib/zammad_api/attribute_access.rb @@ -0,0 +1,121 @@ +# frozen_string_literal: true + +require 'json' + +module ZammadAPI + # Read access to a Zammad record's attributes. + # + # Zammad objects can carry administrator-defined custom attributes, so the + # set of readable attributes is not known ahead of time and is resolved + # through +method_missing+. A reader for an attribute the record does not + # carry raises +NoMethodError+; {#[]}, {#fetch} with a default, and {#key?} + # are the readers for an attribute that may be absent. + module AttributeAccess + # What a writer for an attribute is named: a plain identifier and an `=`, + # so that operators such as +<=+ are not taken for one. + ATTRIBUTE_WRITER = /\A[a-zA-Z_]\w*=\z/ + private_constant :ATTRIBUTE_WRITER + + # All known attributes, deeply frozen. {#to_h} returns a copy that is safe + # to modify; an attribute writer is the way to stage a change. + # + # @return [Hash{Symbol => Object}] + attr_reader :attributes + + # @param key [Symbol, String] + # @return [Object, nil] + def [](key) = attributes[key.to_sym] + + # Stages a change to an attribute, like the attribute writer does. + # + # @param key [Symbol, String] + # @param value [Object] + # @return [Object] the staged value + def []=(key, value) + write_attribute(key.to_sym, value) + end + + # Reads an attribute the way +Hash#fetch+ does. + # + # @param key [Symbol, String] + # @return [Object] + # @raise [KeyError] when the record does not carry the attribute and + # neither a default nor a block is given + def fetch(key, *default, &block) = attributes.fetch(key.to_sym, *default, &block) # steep:ignore UnresolvedOverloading + + # @return [Boolean] + def key?(key) = attributes.key?(key.to_sym) + + # @return [Hash{Symbol => Object}] a deep copy of all attributes, safe to + # modify + def to_h = DeepCopy.writable_copy(attributes) + + # @return [Integer, nil] + def id = attributes[:id] + + # Enables Ruby pattern matching against a record's attributes. + # + # @example + # case client.tickets.find(1) + # in {state: 'closed'} + # nil + # in {state: String => state, priority: '3 high'} + # escalate(state) + # end + # + # @param keys [Array, nil] the keys the pattern asks for + # @return [Hash{Symbol => Object}] + def deconstruct_keys(keys) = keys.nil? ? attributes : attributes.slice(*keys) + + # Whether +other+ is the same Zammad record: the same class, carrying the + # same id. A record with no id is equal only to itself. + # + # @param other [Object] + # @return [Boolean] + def ==(other) + return true if equal?(other) + + other.instance_of?(self.class) && !id.nil? && other.id == id + end + alias eql? == + + # Consistent with {#==}, so that records can be deduplicated with +uniq+, + # collected in a +Set+ and used as Hash keys. + # + # @return [Integer] + def hash + id.nil? ? super : [self.class, id].hash + end + + # @return [Hash{Symbol => Object}] the attributes, for a JSON encoder + def as_json(*) = to_h + + # @return [String] the attributes as a JSON object + def to_json(*args) = to_h.to_json(*args) # steep:ignore UnexpectedPositionalArgument + + def method_missing(name, *args) + identifier = name.to_s + return write_attribute(identifier.delete_suffix('=').to_sym, args.first) if ATTRIBUTE_WRITER.match?(identifier) && args.size == 1 + return attributes[name] if args.empty? && attributes.key?(name) + + super + end + + def respond_to_missing?(name, include_private = false) + identifier = name.to_s + return writable_attributes? if ATTRIBUTE_WRITER.match?(identifier) + + attributes.key?(name) || super + end + + private + + def writable_attributes? = false + + def write_attribute(key, _value) + raise NoMethodError, "#{self.class.name} attributes are read-only (tried to set #{key})" + end + + def frozen_attributes(value) = DeepCopy.frozen_copy(value) + end +end diff --git a/lib/zammad_api/client.rb b/lib/zammad_api/client.rb index b1d6c857..da800cd9 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -1,65 +1,265 @@ -require 'forwardable' - -require 'zammad_api/log' -require 'zammad_api/transport' -require 'zammad_api/dispatcher' -require 'zammad_api/resources' +# frozen_string_literal: true module ZammadAPI + # The entry point of this gem. + # + # @example Token authentication + # client = ZammadAPI::Client.new( + # url: 'https://zammad.example.com/', + # http_token: 'your-access-token' + # ) + # client.tickets.find(1).title + # + # @example Basic authentication with a custom timeout and logger + # client = ZammadAPI::Client.new( + # url: 'https://zammad.example.com/', + # user: 'user@example.com', + # password: 'secret', + # timeout: 10, + # logger: Logger.new($stdout) + # ) class Client - extend Forwardable - - def_delegators :@transport, :on_behalf_of, :on_behalf_of= + # Maps the reader methods of this client to their resource classes. + RESOURCES = { + groups: Resources::Group, + organizations: Resources::Organization, + tickets: Resources::Ticket, + ticket_articles: Resources::TicketArticle, + ticket_priorities: Resources::TicketPriority, + ticket_states: Resources::TicketState, + users: Resources::User + }.freeze - def initialize(config) - @config = config - @logger = ZammadAPI::Log.new(@config) - @transport = ZammadAPI::Transport.new(@config, @logger) - check_config + # @!method groups + # @return [ResourceProxy] proxy for {Resources::Group} + # @!method organizations + # @return [ResourceProxy] proxy for {Resources::Organization} + # @!method tickets + # @return [ResourceProxy] proxy for {Resources::Ticket} + # @!method ticket_articles + # @return [ResourceProxy] proxy for {Resources::TicketArticle} + # @!method ticket_priorities + # @return [ResourceProxy] proxy for {Resources::TicketPriority} + # @!method ticket_states + # @return [ResourceProxy] proxy for {Resources::TicketState} + # @!method users + # @return [ResourceProxy] proxy for {Resources::User} + RESOURCES.each do |name, resource_class| + define_method(name) { @resources.fetch(resource_class) } end - def perform_on_behalf_of(identifier) - self.on_behalf_of = identifier - yield.tap do |_| - self.on_behalf_of = nil + # Environment variables {.from_env} reads, mapped to the options they set. + ENV_OPTIONS = { + 'ZAMMAD_URL' => :url, + 'ZAMMAD_TOKEN' => :http_token, + 'ZAMMAD_OAUTH2_TOKEN' => :oauth2_token, + 'ZAMMAD_USER' => :user, + 'ZAMMAD_PASSWORD' => :password + }.freeze + + # Builds a client from the environment. + # + # Reads {ENV_OPTIONS}; a variable that is empty or blank counts as unset. + # Anything passed in wins over the environment, and credentials passed in + # replace the ones the environment holds. + # + # @example + # ZAMMAD_URL=https://zammad.example.com/ ZAMMAD_TOKEN=secret ruby report.rb + # + # client = ZammadAPI::Client.from_env + # client = ZammadAPI::Client.from_env(timeout: 300) # for one bulk job + # + # @param overrides [Hash] any option accepted by {Config} + # @return [Client] + # @raise [ConfigurationError] when neither the environment nor +overrides+ + # supply a URL and credentials + def self.from_env(**overrides) + from_environment = ENV_OPTIONS.filter_map do |name, option| + value = ENV.fetch(name, nil) + [option, value] if !value.to_s.strip.empty? end + options = Config.merge_options(from_environment.to_h, overrides) + + raise ConfigurationError, "missing url: set ZAMMAD_URL or pass url: to #{name}.from_env" if options[:url].to_s.empty? + + new(**options) end - def method_missing(method, *_args) - method = modulize(method.to_s) - class_name = "ZammadAPI::Resources::#{method}" - begin - class_object = Kernel.const_get(class_name) - rescue - raise ResourceNotFoundError, "Resource for #{method} does not exist" + # @param options [Hash] see {Config} for every supported option + # @option options [String] :url base URL of the Zammad instance + # @option options [String] :http_token access token + # @option options [String] :oauth2_token OAuth2 token + # @option options [String] :user login for basic authentication + # @option options [String] :password password for basic authentication + # @param transport [Transport, nil] the transport of the client this one + # is derived from, in place of options. For {#with} and {#on_behalf_of}. + # @raise [ConfigurationError] when the options are incomplete or invalid, + # or name more than one way to authenticate + def initialize(transport: nil, **options) + @transport = transport || Transport.new(Config.new(**options)) + @resources = RESOURCES.values.to_h { [it, ResourceProxy.new(@transport, it)] }.freeze + end + + # @return [Config] the validated configuration, with credentials redacted + # from its +inspect+ output + def config = @transport.config + + # The proxy for a resource, by name or by class. A class is the way to + # the parts of the API this gem does not model. + # + # @example A resource this gem does not model + # class Role < ZammadAPI::Resources::Base + # path 'api/v1/roles' + # end + # + # client.resource(Role).each { |role| puts role.name } + # + # @param name [Symbol, String, Class] a key of {RESOURCES}, or a subclass + # of {Resources::Base} + # @return [ResourceProxy] + # @raise [UnknownResourceError] when no resource has that name + def resource(name) + return @resources.fetch(name) { ResourceProxy.new(@transport, name) } if name.is_a?(Class) + + resource_class = RESOURCES.fetch(name.to_sym) do + raise UnknownResourceError, "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}" end - ZammadAPI::Dispatcher.new(@transport, class_object) + + @resources.fetch(resource_class) end - private + # @return [Array] every resource name this client supports + def resource_names = RESOURCES.keys - def check_config - raise ConfigurationError, 'missing url in config' if !@config[:url] - raise ConfigurationError, 'config url needs to start with http:// or https://' if !%r{^(http|https)://}.match?(@config[:url]) + # The user these requests authenticate as, or the one {#on_behalf_of} + # scoped them to. + # + # @example Checking which account a token belongs to + # client.me.email # => "agent@example.com" + # + # @return [Resources::User] + # @raise [AuthenticationError] when the credentials are not valid + def me = users.find('me') - # check for token auth - return if @config[:http_token] && !@config[:http_token].empty? - return if @config[:oauth2_token] && !@config[:oauth2_token].empty? + # The version of the Zammad instance, not of this gem — that is + # {ZammadAPI::VERSION}. Zammad serves it to administrators only. + # + # @example + # client.version # => "6.4.0" + # + # @return [String, nil] nil when the instance reported no version + # @raise [AuthorizationError] when the account is not an administrator + def version + @transport.get('api/v1/version').decoded(:object)[:version]&.to_s + end - if !@config[:user] || @config[:user].empty? - raise ConfigurationError, 'missing user in config' - end + # @!group Raw requests + + # Performs a +GET+ against any endpoint of the Zammad API, with the + # client's authentication, retries, JSON decoding and error classes. + # + # @example An endpoint this gem does not model + # client.get('api/v1/roles').body + # # => [{id: 1, name: "Admin", ...}, ...] + # + # @example An endpoint that needs a header of its own + # client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) + # + # @param path [String] path relative to {Config#url}; a leading slash is + # ignored, and an absolute URL is refused, so the client's credentials + # only ever go to the instance it was configured for + # @param query [Hash, nil] query string parameters + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @raise [TransportError] when the request could not be completed + # @raise [ArgumentError] for a path that is an absolute URL + def get(path, query: nil, headers: nil) = @transport.get(path, query: query, headers: headers) + + # Performs a +POST+ against any endpoint of the Zammad API. + # + # @example + # client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) + # + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param body [Hash, Array, String, nil] request payload; a Hash or Array is + # encoded as JSON, a String is sent as it is + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @see #get + def post(path, query: nil, body: nil, headers: nil) = @transport.post(path, query: query, body: body, headers: headers) + + # Performs a +PUT+ against any endpoint of the Zammad API. + # + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param body [Hash, Array, String, nil] request payload; a Hash or Array is + # encoded as JSON, a String is sent as it is + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @see #get + def put(path, query: nil, body: nil, headers: nil) = @transport.put(path, query: query, body: body, headers: headers) + + # Performs a +DELETE+ against any endpoint of the Zammad API. + # + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for any non-2xx response + # @see #get + def delete(path, query: nil, headers: nil) = @transport.delete(path, query: query, headers: headers) - return if @config[:password] && !@config[:password].empty? + # @!endgroup - raise ConfigurationError, 'missing password in config' + # Returns a new client with some configuration options changed. + # + # The options are re-validated, and any {#on_behalf_of} scope is carried + # over. Naming credentials replaces the ones this client has. + # + # @example A longer timeout for one bulk job + # bulk = client.with(timeout: 300, retries: 5) + # + # @param options [Hash] any option accepted by {Config} + # @return [Client] + # @raise [ConfigurationError] when the resulting options are invalid + def with(**options) + self.class.new(transport: @transport.with_config(config.with(**options))) end - def modulize(string) - string.gsub(/__(.?)/) { "::#{$1.upcase}" } - .gsub(%r{/(.?)}) { "::#{$1.upcase}" } - .gsub(/(?:_+|-+)([a-z])/) { $1.upcase } - .gsub(/(\A|\s)([a-z])/) { $1 + $2.upcase } + # Performs requests on behalf of another user, through a new client. + # + # @example Scoped client + # support = client.on_behalf_of('agent@example.com') + # support.tickets.create(title: 'Help', group: 'Users', customer_id: 1) + # + # @example Block form + # client.on_behalf_of('agent@example.com') do |scoped| + # scoped.tickets.find(1) + # end + # + # @param identifier [String, Integer] login, email address or user id + # @yieldparam scoped [Client] + # @return [Client] when no block is given, otherwise the block's value + # @raise [ArgumentError] for an identifier that is nil or blank, which + # would quietly leave the requests unscoped + def on_behalf_of(identifier) + from = identifier.to_s.strip + raise ArgumentError, "on_behalf_of needs the login, email address or id of a user, got #{identifier.inspect}" if from.empty? + + scoped = self.class.new(transport: @transport.with_on_behalf_of(from.freeze)) + return scoped if !block_given? + + yield scoped + end + + def inspect + scope = @transport.on_behalf_of + + "#<#{self.class.name} url=#{config.url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{scope.inspect}" if scope}>" end end end diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb new file mode 100644 index 00000000..25fa0720 --- /dev/null +++ b/lib/zammad_api/collection.rb @@ -0,0 +1,233 @@ +# frozen_string_literal: true + +module ZammadAPI + # A lazily fetched, automatically paginated list of records. + # + # Nothing is requested until the collection is iterated. {#order} and + # {#page} return new collections, so a collection can be built up in + # steps and shared without being disturbed. + # + # {#each} walks every page until the server runs out of records, so it is + # safe to iterate a collection larger than one page. {#first} reads one page + # sized for what it was asked for, and +lazy+, +detect+ and the rest of + # +Enumerable+ stop the walk as soon as they have enough. + # + # @example Iterate every ticket + # client.tickets.all.each { |ticket| puts ticket.title } + # + # @example Narrow to matches, then stop after the first five + # client.tickets.search('state.name:open').first(5) + # + # @example Sorted by the server + # client.groups.order(:name).each { |group| puts group.name } + # + # @example Work in batches, e.g. for an import + # client.tickets.all.in_batches(of: 50) { |tickets| import(tickets) } + # + # @example One explicit page + # client.tickets.all.page(2, per_page: 50).to_a + class Collection + include Enumerable + + # Largest page size Zammad's search endpoints serve. + SEARCH_MAX_PER_PAGE = 200 + + # @api private + # @param per_page [Integer, nil] records fetched per request, or nil for + # as many as the endpoint serves + # @param search [Boolean] whether this is a search endpoint, which can + # serve a short page before the last one, can count its results and + # always sorts + def initialize(transport, resource_class, search: false, query: {}, per_page: nil, page: nil) + max_per_page = search ? SEARCH_MAX_PER_PAGE : resource_class.page_limit + + @transport = transport + @resource_class = resource_class + @search = search + @path = search ? "#{resource_class.resource_path}/search" : resource_class.resource_path + @query = { expand: true }.merge(query) + @per_page = [per_page || max_per_page, max_per_page].min + @page = page + end + + # Yields every record, fetching pages as needed. + # + # @yieldparam record [Resources::Base] + # @return [Enumerator] when no block is given + def each(&block) + return to_enum(:each) if !block + + in_batches { |records| records.each(&block) } + self + end + + # Yields every record, fetching +batch_size+ records per request. + # + # @param batch_size [Integer, nil] + # @yieldparam record [Resources::Base] + # @return [Enumerator] when no block is given + def find_each(batch_size: nil, &block) + return to_enum(:find_each, batch_size: batch_size) if !block + return with(per_page: batch_size).find_each(&block) if batch_size + + each(&block) + end + + # Yields one array of records per page. + # + # @param of [Integer, nil] records fetched per request + # @yieldparam records [Array] + # @return [Enumerator] when no block is given + def in_batches(of: nil, &block) + return to_enum(:in_batches, of: of) if !block + return with(per_page: of).in_batches(&block) if of + + walk(&block) + self + end + + # Returns a new collection limited to a single page. + # + # @example + # client.tickets.all.page(2, per_page: 50).to_a + # + # @param number [Integer] one-based page number + # @param per_page [Integer, nil] records on the page, at most what the + # endpoint serves + # @return [Collection] + def page(number, per_page: nil) = with(page: number, per_page: per_page || @per_page) + + # Returns a new collection sorted by the server. + # + # Attributes named on their own sort ascending, and a keyword says which + # way one runs. A second +order+ sorts within the first. + # + # @example + # client.groups.order(:name).first(5) + # client.organizations.order(name: :desc) + # + # @param attributes [Array] attributes to sort by, ascending + # @param directions [Hash{Symbol => Symbol, String}] attributes to sort by, + # each with +:asc+ or +:desc+ + # @return [Collection] + # @raise [ArgumentError] for an endpoint that does not sort + def order(*attributes, **directions) + raise ArgumentError, "#{@path} is always served in the same order and ignores sort_by" if !@search && !@resource_class.sortable? + + requested = attributes.to_h { [it.to_s, 'asc'] }.merge(directions.to_h { |name, direction| [name.to_s, direction.to_s] }) + columns = sorted_by.merge(requested) + with(query: @query.merge(sort_by: columns.keys.join(','), order_by: columns.values.join(','))) + end + + # Reads one or more attributes from every record. + # + # @example + # client.users.all.pluck(:email) # => ["a@example.com", ...] + # client.tickets.all.pluck(:id, :title) # => [[1, "Help"], ...] + # + # @param keys [Array] attribute names + # @return [Array] + def pluck(*keys) + return map { it[keys.first] } if keys.one? + + map { |record| keys.map { record[it] } } + end + + # The first record, or the first +count+ of them, read with a request sized + # for what was asked rather than a whole page. + # + # @param count [Integer, nil] + # @return [Resources::Base, Array, nil] + def first(count = nil) + source = @page ? self : with(per_page: count || 1) + + count.nil? ? source.each.first : source.each.first(count) + end + + # +Enumerable#find+, which takes a block. Look a record up by id on the + # resource instead: +client.tickets.find(1)+. + # + # @yieldparam record [Resources::Base] + # @return [Resources::Base, nil] + # @raise [ArgumentError] when given an id where a block belongs + def find(*args, &block) + raise ArgumentError, "find on a collection takes a block; look a record up by id with client..find(#{args.first.inspect})" if block.nil? && !args.empty? + + super + end + + # Number of records in this collection: one request on a search, which + # Zammad can count without serving the records, and a walk otherwise. + # + # There is no +size+ or +length+: +each_slice+ and +each_cons+ ask for + # the size before they start, and that would read every record twice. + # + # @return [Integer] + def count(*args, &block) + return super if !args.empty? || block || @page || !@search + + total_count || super + end + + # @return [Boolean] whether the collection holds no records, read with + # one request for one record + def empty? = first.nil? + + def inspect + "#<#{self.class.name} #{@resource_class.name} path=#{@path.inspect} per_page=#{@per_page}#{" page=#{@page}" if @page}>" + end + + private + + # Fetches page after page until one comes back empty. An index also stops + # at a short page; a search can serve one before the last. + # + # Not `loop`, which would end the walk quietly on a StopIteration raised + # by the caller's block; and the page is judged before the block gets it, + # since the block may change the Array. + def walk + number = @page || 1 + previous = nil + last = false + + until last + records = fetch(number) + break if records.empty? + + ids = records.map(&:id) + raise PaginationError, repeated_page_message(number) if ids == previous + + last = !@page.nil? || (!@search && records.size < @per_page) + yield records + + previous = ids + number += 1 + end + end + + def fetch(number) + response = @transport.get(@path, query: @query.merge(page: number, per_page: @per_page)) + + response.decoded(:array).map { @resource_class.from_response(@transport, it) } + end + + def repeated_page_message(number) + "#{@path}: page #{number} repeated page #{number - 1}, so the endpoint is ignoring the page parameter. " \ + 'If it serves every record in one response, read it with client.get instead.' + end + + def total_count + response = @transport.get(@path, query: @query.merge(only_total_count: true)) + total = response.body.is_a?(Hash) ? response.body[:total_count] : nil + total if total.is_a?(Integer) + end + + def sorted_by + @query.fetch(:sort_by, '').to_s.split(',').zip(@query.fetch(:order_by, '').to_s.split(',')).to_h + end + + def with(page: @page, per_page: @per_page, query: @query) + self.class.new(@transport, @resource_class, search: @search, query: query, per_page: per_page, page: page) + end + end +end diff --git a/lib/zammad_api/config.rb b/lib/zammad_api/config.rb new file mode 100644 index 00000000..ecbaa2fc --- /dev/null +++ b/lib/zammad_api/config.rb @@ -0,0 +1,239 @@ +# frozen_string_literal: true + +require 'logger' +require 'uri' + +module ZammadAPI + # Immutable, validated client configuration. + # + # Credentials are never included in {#inspect} output, so configuration + # objects are safe to log or attach to exception reports. + # + # @example + # ZammadAPI::Config.new(url: 'https://zammad.example.com/', http_token: 'secret') + # + # @!attribute [r] url + # @return [String] base URL, always with a trailing slash + # @!attribute [r] user + # @return [String, nil] login for basic authentication + # @!attribute [r] password + # @return [String, nil] password for basic authentication + # @!attribute [r] http_token + # @return [String, nil] Zammad access token + # @!attribute [r] oauth2_token + # @return [String, nil] OAuth2 bearer token + # @!attribute [r] user_agent + # @return [String] value of the +User-Agent+ request header + # @!attribute [r] timeout + # @return [Numeric] seconds to wait for a response + # @!attribute [r] open_timeout + # @return [Numeric] seconds to wait for the connection + # @!attribute [r] retries + # @return [Integer] retry attempts for a request that only reads + # @!attribute [r] retry_interval + # @return [Numeric] seconds before the first retry, doubling after that + # up to {#timeout}, with up to half of it added as jitter + # @!attribute [r] ssl_verify + # @return [Boolean] whether TLS certificates are verified + # @!attribute [r] proxy + # @return [String, nil] proxy URL + # @!attribute [r] adapter + # @return [Symbol, nil] name of the Faraday adapter, +nil+ for Faraday's default + # @!attribute [r] middleware + # @return [Proc, nil] called with the Faraday connection while it is + # being built, after this gem's own middleware + # @!attribute [r] logger + # @return [Logger] where debug output goes + Config = Data.define( + :url, + :user, + :password, + :http_token, + :oauth2_token, + :user_agent, + :timeout, + :open_timeout, + :retries, + :retry_interval, + :ssl_verify, + :proxy, + :adapter, + :middleware, + :logger + ) + + class Config + # Seconds to wait for a response. + DEFAULT_TIMEOUT = 60 + + # Seconds to wait for the connection. + DEFAULT_OPEN_TIMEOUT = 10 + + # Retry attempts for a request that only reads. + DEFAULT_RETRIES = 2 + + # Seconds before the first retry. + DEFAULT_RETRY_INTERVAL = 0.5 + + # Value of the +User-Agent+ header unless one is configured. + DEFAULT_USER_AGENT = "zammad_api-ruby/#{ZammadAPI::VERSION}".freeze + + # What {#inspect} and the log show in place of a credential. + REDACTION = '[REDACTED]' + + # The options of each way to authenticate. + CREDENTIAL_OPTIONS = { + http_token: %i[http_token], + oauth2_token: %i[oauth2_token], + basic: %i[user password] + }.freeze + + # Lays +overrides+ over +options+, dropping the credentials they replace. + # + # A configuration authenticates one way, so an override that names one + # takes the place of every other. The options of its own scheme are kept, + # so overriding +password:+ alone still pairs it with the +user+ there. + # + # @api private + # @param options [Hash{Symbol => Object}] the options being overridden + # @param overrides [Hash{Symbol => Object}] + # @return [Hash{Symbol => Object}] + def self.merge_options(options, overrides) + named = CREDENTIAL_OPTIONS.select { |_, keys| keys.any? { !overrides[it].to_s.strip.empty? } } + replaced = named.empty? ? [] : CREDENTIAL_OPTIONS.except(*named.keys).values.flatten + + options.except(*replaced).merge(overrides) + end + + # @param url [String] base URL of the Zammad instance + # @param user [String, nil] login for basic authentication + # @param password [String, nil] password for basic authentication + # @param http_token [String, nil] Zammad access token + # @param oauth2_token [String, nil] OAuth2 bearer token + # @param user_agent [String, nil] value of the +User-Agent+ header + # @param timeout [Numeric] seconds to wait for a response + # @param open_timeout [Numeric] seconds to wait for the connection + # @param retries [Integer] retry attempts for a request that only reads + # @param retry_interval [Numeric] seconds before the first retry + # @param ssl_verify [Boolean] whether TLS certificates are verified + # @param proxy [String, nil] proxy URL + # @param adapter [Symbol, String, nil] name of a Faraday adapter + # @param middleware [#call, nil] called with the Faraday connection while it is built + # @param logger [Logger, nil] where debug output goes; discarded by default + # @raise [ConfigurationError] when the options are incomplete or invalid + def initialize( + url: nil, + user: nil, + password: nil, + http_token: nil, + oauth2_token: nil, + user_agent: nil, + timeout: DEFAULT_TIMEOUT, + open_timeout: DEFAULT_OPEN_TIMEOUT, + retries: DEFAULT_RETRIES, + retry_interval: DEFAULT_RETRY_INTERVAL, + ssl_verify: true, + proxy: nil, + adapter: nil, + middleware: nil, + logger: nil + ) + # RBS cannot describe the initializer that Data.define generates. + # steep:ignore:start + super( + url: normalize_url(url), + user: present(user), + password: present(password), + http_token: stripped(http_token), + oauth2_token: stripped(oauth2_token), + user_agent: stripped(user_agent) || DEFAULT_USER_AGENT, + timeout: timeout, + open_timeout: open_timeout, + retries: retries, + retry_interval: retry_interval, + ssl_verify: ssl_verify, + proxy: present(proxy), + adapter: present(adapter)&.to_sym, + middleware: middleware, + logger: logger || Logger.new(IO::NULL) + ) + # steep:ignore:end + + validate_credentials! + end + + # @return [Symbol] +:http_token+, +:oauth2_token+ or +:basic+ + def authentication_scheme + return :http_token if http_token + return :oauth2_token if oauth2_token + + :basic + end + + # Returns a copy with some options changed, re-validated. Naming one way + # to authenticate replaces the one this configuration had. + # + # @param options [Hash] any option this class accepts + # @return [Config] + # @raise [ConfigurationError] when the resulting options are invalid + def with(**options) = self.class.new(**self.class.merge_options(to_h, options)) + + # @return [String] configuration description with credentials redacted + def inspect + rendered = to_h.map { |key, value| "#{key}=#{render(key, value)}" } + "#" + end + alias to_s inspect + + # What +pp+, and so a console, prints: {#inspect}, rather than every member. + # + # @api private + # @param printer [PP] + # @return [void] + def pretty_print(printer) = printer.text(inspect) + + private + + def render(key, value) + return value.inspect if value.nil? + + case key + when :password, :http_token, :oauth2_token then REDACTION + when :proxy then value.to_s.sub(%r{//[^/@]*@}, "//#{REDACTION}@").inspect + when :logger, :middleware then "#<#{value.class}>" + else value.inspect + end + end + + def normalize_url(value) + raise ConfigurationError, 'missing url in config' if value.to_s.empty? + + uri = URI.parse(value.to_s) + raise ConfigurationError, 'config url needs to start with http:// or https:// and name a host' if !uri.is_a?(URI::HTTP) || uri.host.to_s.empty? + raise ConfigurationError, 'config url carries credentials: pass user: and password:, or a token, instead' if uri.userinfo + + value.end_with?('/') ? value : "#{value}/" + rescue URI::InvalidURIError + raise ConfigurationError, 'config url is not a valid URL' + end + + def validate_credentials! + given = CREDENTIAL_OPTIONS.select { |_, options| options.any? { !public_send(it).nil? } }.keys + if given.size > 1 + named = given.map { CREDENTIAL_OPTIONS.fetch(it).join(' and ') }.join(', ') + raise ConfigurationError, "config names more than one way to authenticate (#{named}): pass http_token:, or oauth2_token:, or user: and password:" + end + return if http_token || oauth2_token + + raise ConfigurationError, 'missing user in config' if user.nil? + raise ConfigurationError, 'missing password in config' if password.nil? + end + + def present(value) = value.nil? || value.to_s.empty? ? nil : value + + def stripped(value) + text = value.to_s.strip + text.empty? ? nil : text + end + end +end diff --git a/lib/zammad_api/deep_copy.rb b/lib/zammad_api/deep_copy.rb new file mode 100644 index 00000000..05846ae2 --- /dev/null +++ b/lib/zammad_api/deep_copy.rb @@ -0,0 +1,43 @@ +# frozen_string_literal: true + +module ZammadAPI + # Recursive copies of the plain JSON structures this gem passes around. + # + # @api private + module DeepCopy + module_function + + # A frozen deep copy, so a record's attributes cannot change behind its + # back. Hash keys become Symbols, so that caller-supplied attributes + # behave the same as decoded responses. Strings are copied before they + # are frozen, so the caller's own values are left alone. + # + # @param value [Object] + # @return [Object] a frozen copy + def frozen_copy(value) + case value + when Hash then value.to_h { |key, nested| [symbolize(key), frozen_copy(nested)] }.freeze + when Array then value.map { frozen_copy(it) }.freeze + when String then value.dup.freeze + else value + end + end + + # A writable deep copy of a frozen structure. + # + # @param value [Object] + # @return [Object] + def writable_copy(value) + case value + when Hash then value.to_h { |key, nested| [key, writable_copy(nested)] } + when Array then value.map { writable_copy(it) } + when String then value.dup + else value + end + end + + # @param key [Object] + # @return [Object] the key as a Symbol, where it converts to one + def symbolize(key) = key.respond_to?(:to_sym) ? key.to_sym : key + end +end diff --git a/lib/zammad_api/dispatcher.rb b/lib/zammad_api/dispatcher.rb deleted file mode 100644 index 07b311b9..00000000 --- a/lib/zammad_api/dispatcher.rb +++ /dev/null @@ -1,12 +0,0 @@ -module ZammadAPI - class Dispatcher - def initialize(transport, resource) - @transport = transport - @resource = resource - end - - def method_missing(method, *args) - @resource.send(method, @transport, args[0]) - end - end -end diff --git a/lib/zammad_api/errors.rb b/lib/zammad_api/errors.rb index 4e07e1d2..111930b2 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -1,62 +1,124 @@ -require 'json' +# frozen_string_literal: true module ZammadAPI - class Error < RuntimeError; end + # Base class for every error raised by this gem. + # + # Rescuing +ZammadAPI::Error+ catches all of them. + class Error < StandardError; end + # Raised when {Config} cannot be built from the supplied options. class ConfigurationError < Error; end - class ResourceNotFoundError < Error; end + # Raised when a resource name is requested that this client does not know + # about, e.g. +client.unicorn+. + class UnknownResourceError < Error; end + # Base class for failures that prevented a request from completing. + class TransportError < Error; end + + # Raised when the connection to the Zammad instance could not be + # established: DNS, a refused connection, a TLS failure, or no connection + # within {Config#open_timeout}. + class ConnectionError < TransportError; end + + # Raised when a response took longer than {Config#timeout}. + class TimeoutError < TransportError; end + + # Raised when a response did not have the shape the caller expected. + class ParseError < Error; end + + # Raised when an endpoint answers a page request with the same records as + # the page before it. It is ignoring +page+ then, and a walk would never end. + class PaginationError < Error; end + + # Base class for errors carrying an HTTP response. + # + # Use {.build} rather than +new+ to get the most specific subclass for a + # given status code. class ResponseError < Error - attr_reader :response, :operation, :resource_class + # @return [Response, nil] the decoded HTTP response + attr_reader :response - def initialize(operation:, response:, resource_class: nil) - @operation = operation - @response = response - @resource_class = resource_class - super(default_message) + # Returns the most specific error class for +response+ and instantiates it. + # + # @param response [Response] + # @param request [String] the request that was answered, such as + # +"GET api/v1/tickets/1"+ + # @return [ResponseError] + def self.build(response, request) + error_class = STATUS_ERRORS.fetch(response.status) { response.status >= 500 ? ServerError : ClientError } + + error_class.new("#{request} failed", response: response) + end + + # @param message [String] what failed. What the response says about it, + # Zammad's own message or the status, is added to it. + # @param response [Response, nil] + def initialize(message, response: nil) + @response = response + super(response ? "#{message}: #{server_message || "HTTP #{status}"}" : message) end + # The status of the response, or, for an error raised without one such as + # {ResourceProxy#find_by!} finding nothing, the status its class stands for. + # + # @return [Integer, nil] HTTP status code def status - response&.status + response&.status || STATUS_ERRORS.key(self.class) end + # @return [Hash, String, nil] parsed JSON body, or the raw body for + # non-JSON responses def body response&.body end - def self.from(response, **kwargs) - klass = if response.nil? - self - elsif response.status >= 500 - ServerError - else - ClientError - end - klass.new(response: response, **kwargs) + # @return [Hash] response headers, empty when there is no response + def headers + response&.headers || {} end - private + # @return [String, nil] the error message reported by Zammad, if any + def server_message + return nil if !body.is_a?(Hash) - def default_message - subject = resource_class ? "#{operation} (#{resource_class.name})" : operation - "Can't #{subject}: #{detail}" + value = body[:error_human] || body[:error] + value.to_s.empty? ? nil : value.to_s end + end - def detail - body_error || "HTTP #{status}" - end + # Any 4xx response that has no more specific subclass. + class ClientError < ResponseError; end - def body_error - return nil if body.to_s.strip.empty? + # Any 5xx response. + class ServerError < ResponseError; end - parsed = JSON.parse(body) - parsed.is_a?(Hash) ? parsed['error'] : nil - rescue JSON::ParserError - nil - end + # 401 - credentials missing, wrong, or expired. + class AuthenticationError < ClientError; end + + # 403 - authenticated, but not permitted to perform the operation. + class AuthorizationError < ClientError; end + + # 404 - the requested record does not exist. + class NotFoundError < ClientError; end + + # 422 - Zammad rejected the submitted attributes. + class ValidationError < ClientError; end + + # 429 - too many requests. + class RateLimitError < ClientError + # @return [Integer, nil] value of the +Retry-After+ response header, in seconds + def retry_after = Integer(headers['retry-after'].to_s, 10, exception: false) end - class ClientError < ResponseError; end - class ServerError < ResponseError; end + class ResponseError + STATUS_ERRORS = { + 401 => AuthenticationError, + 403 => AuthorizationError, + 404 => NotFoundError, + 422 => ValidationError, + 429 => RateLimitError + }.freeze + private_constant :STATUS_ERRORS + end end diff --git a/lib/zammad_api/json_helper.rb b/lib/zammad_api/json_helper.rb deleted file mode 100644 index fd8ca4cc..00000000 --- a/lib/zammad_api/json_helper.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'json' - -module ZammadAPI - module JsonHelper - def safe_json_parse(string) - JSON.parse(string) - rescue JSON::ParserError - {} - end - end -end diff --git a/lib/zammad_api/list_all.rb b/lib/zammad_api/list_all.rb deleted file mode 100644 index 393c56a1..00000000 --- a/lib/zammad_api/list_all.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'zammad_api/list_base' - -module ZammadAPI - class ListAll < ListBase - private - - def perform_request(parameter) - request('all', @url, parameter) - end - end -end diff --git a/lib/zammad_api/list_base.rb b/lib/zammad_api/list_base.rb deleted file mode 100644 index c8b692c4..00000000 --- a/lib/zammad_api/list_base.rb +++ /dev/null @@ -1,84 +0,0 @@ -require 'zammad_api/json_helper' - -module ZammadAPI - class ListBase - include Enumerable - include ZammadAPI::JsonHelper - - def initialize(resource, transport, parameter = {}) - @resource = resource - @url = @resource.get_url - @transport = transport - @parameter = { - page: 1, - per_page: 10, - expand: 'true', - }.merge(parameter) - end - - def [](position) - local_parameter = @parameter.merge( - page: position + 1, - per_page: 1 - ) - perform_request(local_parameter)[0] - end - - def page(page, per_page, &block) - @parameter[:page] = page - @parameter[:per_page] = per_page - fetch_and_yield_each(&block) - end - - def page_next(&block) - @parameter[:page] += 1 - fetch_and_yield_each(&block) - end - - def page_prev(&block) - @parameter[:page] -= 1 - fetch_and_yield_each(&block) - end - - def each(&block) - fetch_and_yield_each(&block) - end - - private - - def fetch_and_yield_each(&block) - result = perform_request(@parameter) - result.each(&block) - end - - def request(request, url, parameter) - # convert parameters into a GET query - url += '?' + parameter.map { |key, value| - if !value.is_a? String - value = value.to_s - end - - "#{key}=#{CGI.escape value}" - }.join('&') - - response = @transport.get(url: url) - if response.status != 200 - raise ResponseError.from(response, operation: "get .#{request} of object", resource_class: @resource.class) - end - - data = safe_json_parse(response.body) - - list = [] - data.each do |local_data| - item = @resource.new(@transport, local_data) - item.new_instance = false - list.push item - end - list - end - - def perform_request(_parameter) - raise Error, "no perform_request implementation for #{self.class.name} found" - end - end -end diff --git a/lib/zammad_api/list_search.rb b/lib/zammad_api/list_search.rb deleted file mode 100644 index fac7f2bb..00000000 --- a/lib/zammad_api/list_search.rb +++ /dev/null @@ -1,11 +0,0 @@ -require 'zammad_api/list_base' - -module ZammadAPI - class ListSearch < ListBase - private - - def perform_request(parameter) - request('search', "#{@url}/search", parameter) - end - end -end diff --git a/lib/zammad_api/log.rb b/lib/zammad_api/log.rb deleted file mode 100644 index b67ad263..00000000 --- a/lib/zammad_api/log.rb +++ /dev/null @@ -1,18 +0,0 @@ -module ZammadAPI - class Log - def initialize(config) - return if !config[:logger] - - require 'logger' - @logger = Logger.new($stderr) - #@logger.level = Logger::WARN - @logger.level = Logger::DEBUG - end - - def method_missing(method, *args) - return if !@logger - - @logger.send(method, args) - end - end -end diff --git a/lib/zammad_api/resource_proxy.rb b/lib/zammad_api/resource_proxy.rb new file mode 100644 index 00000000..375fae9c --- /dev/null +++ b/lib/zammad_api/resource_proxy.rb @@ -0,0 +1,195 @@ +# frozen_string_literal: true + +module ZammadAPI + # Entry point for working with one kind of Zammad record. + # + # Obtained from {Client}, e.g. +client.tickets+, and exposes the operations + # that are not tied to an individual record. + # + # @example + # client.groups.find(1) + # client.groups.create(name: 'Support') + # client.groups.all.each { |group| puts group.name } + # client.groups.order(:name).first(5) + # client.groups.search('support').first + # + # A proxy is +Enumerable+ over {#all}, so the collection surface is reachable + # without naming it: + # + # @example + # client.groups.each { |group| puts group.name } + # client.groups.first(5) + # client.groups.map(&:name) + # client.groups.find_each(batch_size: 500) { |group| archive(group) } + # + # {#find} takes an id and is not +Enumerable#find+; +detect+ is still the + # block form. + class ResourceProxy + include Enumerable + + # @return [Class] the resource class this proxy operates on + attr_reader :resource_class + + # @api private + def initialize(transport, resource_class) + @transport = transport + @resource_class = resource_class + end + + # Builds an unsaved record. + # + # @param attributes [Hash] + # @return [Resources::Base] + def new(attributes = {}) + resource_class.new(@transport, attributes) + end + + # Builds and immediately saves a record. + # + # This raises when Zammad rejects the attributes. Use +new+ and + # {Resources::Base#save} to branch on a validation failure instead. + # + # @param attributes [Hash] + # @return [Resources::Base] + # @raise [ResponseError] when Zammad rejected the request + def create(attributes = {}) + record = new(attributes) + record.save! + record + end + + # Fetches a single record by id. + # + # @param id [Integer, String] + # @return [Resources::Base] + # @raise [NotFoundError] when no such record exists + def find(id) + response = @transport.get(resource_class.member_path(id), query: { expand: true }) + + resource_class.from_response(@transport, response.decoded(:object)) + end + + # The first record carrying all of these attribute values, or nil. + # + # An +id:+ is read with {#find}, in one request. Otherwise, where the + # resource can be searched, the longest String value is the + # search term and the hits are checked against every value. Otherwise + # the index is walked until a record matches. Values are compared + # exactly, and a record that does not carry an attribute does not match it. + # + # @example + # client.users.find_by(email: 'someone@example.com') + # client.ticket_states.find_by(name: 'open') + # + # @param params [Hash{Symbol => Object}] + # @return [Resources::Base, nil] + # @raise [ArgumentError] when no attribute was given + def find_by(**params) + raise ArgumentError, 'find_by needs at least one attribute to match' if params.empty? + return find_by_id(params) if params.key?(:id) + + term = params.values.grep(String).reject { it.strip.empty? }.max_by(&:length) + candidates = resource_class.searchable? && term ? search(term) : all + + candidates.detect { |record| params.all? { |key, value| record.key?(key) && record[key] == value } } + end + + # Like {#find_by}, but raises when nothing matched. + # + # @param params [Hash{Symbol => Object}] + # @return [Resources::Base] + # @raise [NotFoundError] when no record matched + def find_by!(**params) + find_by(**params) || raise(NotFoundError, "no #{resource_class.name} matched #{params.keys.join(' and ')}") + end + + # @param id [Integer, String] + # @return [Boolean] whether a record with that id exists and can be read + def exists?(id) + find(id) + true + rescue NotFoundError + false + end + + # Deletes a record by id, without reading it first. + # + # @param id [Integer, String] + # @return [true] + # @raise [NotFoundError] when no such record exists + def destroy(id) + @transport.delete(resource_class.member_path(id)) + true + end + + # Every record of this kind, as a lazily paginated collection. + # + # @return [Collection] + def all = Collection.new(@transport, resource_class) + + # @!group Collection shorthands, each forwarded to {#all} + + # A forward hands on a block or a count that may be nil, which is what picks + # the overload on the collection, and Steep cannot follow that through. + + # (see Collection#order) + def order(*attributes, **directions) = all.order(*attributes, **directions) + + # (see Collection#each) + def each(&block) = all.each(&block) # steep:ignore BlockTypeMismatch + + # (see Collection#find_each) + def find_each(batch_size: nil, &block) = all.find_each(batch_size: batch_size, &block) # steep:ignore BlockTypeMismatch + + # (see Collection#in_batches) + def in_batches(of: nil, &block) = all.in_batches(of: of, &block) # steep:ignore BlockTypeMismatch + + # (see Collection#page) + def page(number, per_page: nil) = all.page(number, per_page: per_page) + + # (see Collection#pluck) + def pluck(*keys) = all.pluck(*keys) + + # (see Collection#empty?) + def empty? = all.empty? + + # (see Collection#first) + def first(count = nil) = all.first(count) # steep:ignore ArgumentTypeMismatch + + # @!endgroup + + # Records matching a Zammad search term, as a lazily paginated collection. + # + # Keywords are passed to the search endpoint as they are, for what it + # narrows by besides the term, such as +condition:+ and +ids:+, or + # +role_ids:+ for users. + # + # @example + # client.tickets.search('state.name:open').first(10) + # client.users.search('smith', role_ids: [2]) + # + # @param term [String] a Zammad search query; +'*'+ matches every record + # @param filters [Hash{Symbol => Object}] further search parameters + # @return [Collection] + # @raise [Error] for a resource Zammad routes no search endpoint for + # @raise [ArgumentError] for a blank term, which Zammad reads as no term + # and answers with every record + def search(term, **filters) + raise Error, "Zammad routes no search endpoint for #{resource_class.name}: look a record up with find_by, which walks the records instead" if !resource_class.searchable? + raise ArgumentError, "search needs a non-empty query string. Search for '*' to ask for every record." if !term.is_a?(String) || term.strip.empty? + + Collection.new(@transport, resource_class, search: true, query: { query: term, **filters }) + end + + def inspect = "#<#{self.class.name} #{resource_class.name}>" + + private + + def find_by_id(params) + record = find(params.fetch(:id)) + record if params.except(:id).all? { |key, value| record.key?(key) && record[key] == value } + rescue NotFoundError + nil + end + end +end diff --git a/lib/zammad_api/resources.rb b/lib/zammad_api/resources.rb index 8106a4de..f388c7d9 100644 --- a/lib/zammad_api/resources.rb +++ b/lib/zammad_api/resources.rb @@ -1,17 +1,17 @@ -require 'zammad_api/list_base' -require 'zammad_api/list_all' -require 'zammad_api/list_search' -require 'zammad_api/resources/base' -require 'zammad_api/resources/user' -require 'zammad_api/resources/group' -require 'zammad_api/resources/organization' -require 'zammad_api/resources/ticket' -require 'zammad_api/resources/ticket_article' -require 'zammad_api/resources/ticket_article_attachment' -require 'zammad_api/resources/ticket_state' -require 'zammad_api/resources/ticket_priority' +# frozen_string_literal: true + +require_relative 'resources/base' +require_relative 'resources/group' +require_relative 'resources/organization' +require_relative 'resources/ticket' +require_relative 'resources/ticket_article' +require_relative 'resources/ticket_article_attachment' +require_relative 'resources/ticket_priority' +require_relative 'resources/ticket_state' +require_relative 'resources/user' module ZammadAPI - class Resource # rubocop:disable Lint/EmptyClass + # Namespace for the Zammad record classes. + module Resources end end diff --git a/lib/zammad_api/resources/base.rb b/lib/zammad_api/resources/base.rb index 2652c4d6..1a47ff58 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -1,140 +1,243 @@ -require 'cgi' -require 'zammad_api/json_helper' -require 'zammad_api/transport' +# frozen_string_literal: true module ZammadAPI module Resources + # Shared behaviour for every Zammad record. + # + # Attributes are read and written through +method_missing+, because Zammad + # records can carry administrator-defined custom attributes: + # + # group = client.groups.find(1) + # group.name # read + # group.name = 'Support' # stage a change + # group.changed? # => true + # group.save # persist class Base - include ZammadAPI::JsonHelper - extend ZammadAPI::JsonHelper - - attr_accessor :new_instance, :url, :attributes - attr_reader :changes + include AttributeAccess + + # Largest page size Zammad's generic index endpoints serve. Resources + # whose endpoint caps lower declare +max_per_page+. + DEFAULT_MAX_PER_PAGE = 1000 + + # The validation failure from the most recent {#save}, so that a +false+ + # return value can be acted on. + # + # @return [ValidationError, nil] + attr_reader :error + + class << self + # Each declaration defines the reader of the same setting on this + # class, which a subclass inherits and can declare again. + + # Declares the API path of this resource, relative to the instance URL. + # + # @param value [String] + # @return [void] + def path(value) = define_singleton_method(:resource_path) { value } + + # Declares whether Zammad routes a +/search+ endpoint for this resource. + # + # @param value [Boolean] + # @return [void] + def searchable(value) = define_singleton_method(:searchable?) { value } + + # Declares the largest page size this resource's index endpoint serves. + # + # @param value [Integer] + # @return [void] + def max_per_page(value) = define_singleton_method(:page_limit) { value } + + # Declares whether this resource's index endpoint reads +sort_by+ and + # +order_by+. One that does not is refused by {Collection#order}. + # + # @param value [Boolean] + # @return [void] + def sortable(value) = define_singleton_method(:sortable?) { value } + + # @return [String] the API path of this resource + # @raise [Error] when the resource declares none + def resource_path = raise(Error, "#{name} does not declare an API path") + + # @return [Boolean] whether Zammad routes a +/search+ endpoint here + def searchable? = false + + # @return [Integer] the largest page size this endpoint serves + def page_limit = DEFAULT_MAX_PER_PAGE + + # @return [Boolean] whether the index endpoint reads +sort_by+ and +order_by+ + def sortable? = true + + # The API path of one record of this kind, with the id escaped. + # + # @api private + # @param id [Integer, String] + # @return [String] + def member_path(id) = "#{resource_path}/#{Transport.escape_path_segment(id)}" + + # Builds a record that is already stored in Zammad. + # + # @api private + # @param transport [Transport] + # @param attributes [Hash] + # @return [Base] + def from_response(transport, attributes) + record = new(transport, attributes) + record.send(:mark_persisted!) + record + end + end + # @param transport [Transport] + # @param attributes [Hash, nil] or what converts to a Hash, such as + # permitted `ActionController::Parameters` def initialize(transport, attributes = {}) - @new_instance = true - @transport = transport - @changes = {} - @url = self.class.get_url - - if attributes.nil? - attributes = {} - end - @attributes = attributes - symbolize_keys_deep!(@attributes) + @transport = transport + @attributes = frozen_attributes(Hash(attributes)) # steep:ignore UnresolvedOverloading + @baseline = @attributes + @new_record = true + @destroyed = false + @error = nil end - def method_missing(method, *args) - return @attributes[method] if !method.to_s.end_with?('=') + # @return [Boolean] whether this record has not been stored yet + def new_record? = @new_record - method = method.to_s[0, method.length - 1].to_sym - @changes[method] = [@attributes[method], args[0]] - @attributes[method] = args[0] - nil - end + # Whether this record exists in Zammad: false both before the first save + # and after {#destroy}. + # + # @return [Boolean] + def persisted? = !@new_record && !@destroyed - def new_record? - @new_instance - end + # @return [Boolean] whether {#destroy} removed this record from Zammad + def destroyed? = @destroyed - def changed? - !@changes.to_h.empty? + # Staged changes as +attribute => [old_value, new_value]+. + # + # @return [Hash{Symbol => Array(Object, Object)}] + def changes + @attributes.filter_map { |key, value| [key, [@baseline[key], value].freeze] if !@baseline.key?(key) || @baseline[key] != value }.to_h.freeze end - def destroy - response = @transport.delete(url: "#{@url}/#{@attributes[:id]}") - return true if response.status == 200 + # @return [Boolean] whether there are staged changes + def changed? = !changes.empty? - raise ResponseError.from(response, operation: 'destroy object', resource_class: self.class) + # Stages several changes at once. + # + # @param attributes [Hash] + # @return [self] + def assign_attributes(attributes) + Hash(attributes).each { |key, value| write_attribute(DeepCopy.symbolize(key), value) } + self end + # Persists this record, creating it if it is new. + # + # @return [Boolean] false when Zammad rejected the attributes; see {#error} + # @raise [ResponseError] for any other failure def save - attributes = saved_attributes - symbolize_keys_deep!(attributes) - attributes.delete(:article) - @attributes = attributes - @new_instance = false - @changes = {} - true - end - - def self.get_url - @url - end + save! + rescue ValidationError => e + @error = e + false + end + + # Persists this record, creating it if it is new. An existing record + # sends only the attributes that changed, and nothing when none did. + # + # @return [true] + # @raise [ValidationError] when Zammad rejected the attributes + def save! + @error = nil + + if new_record? + response = transport.post(self.class.resource_path, query: { expand: true }, body: @attributes) + else + unsaved = changes.transform_values(&:last) + return true if unsaved.empty? + + response = transport.put(member_path, query: { expand: true }, body: unsaved) + end - def self.url(value) - @url = value + load_response!(response) + true end - def self.all(transport, _) - ZammadAPI::ListAll.new(self, transport, per_page: 100) + # Stages the attributes and saves. + # + # @param attributes [Hash] + # @return [Boolean] see {#save} + def update(attributes) + assign_attributes(attributes) + save end - def self.search(transport, parameter) - ZammadAPI::ListSearch.new(self, transport, parameter) + # Stages the attributes and saves. + # + # @param attributes [Hash] + # @return [true] + # @raise [ValidationError] see {#save!} + def update!(attributes) + assign_attributes(attributes) + save! end - def self.find(transport, id) - response = transport.get(url: "#{@url}/#{id}?expand=true") - if response.status != 200 - raise ResponseError.from(response, operation: 'find object', resource_class: self) - end + # Reads this record again, dropping staged changes. + # + # @return [self] + # @raise [Error] when the record is new + def reload + raise_if_new!('reload') - data = safe_json_parse(response.body) - item = new(transport, data) - item.new_instance = false - item + load_response!(transport.get(member_path, query: { expand: true })) + self end - def self.create(transport, data) - item = new(transport, data) - item.save - item - end + # Deletes this record in Zammad. + # + # @return [true] + # @raise [Error] when the record is new + def destroy + raise_if_new!('destroy') - def self.destroy(transport, id) - item = find(transport, id) - item.destroy + transport.delete(member_path) + @destroyed = true true end + def inspect = "#<#{self.class.name} id=#{id.inspect} new_record=#{new_record?}#{' destroyed=true' if destroyed?} attributes=#{Transport.redact(attributes).inspect}>" + private - def saved_attributes - return save_new if @new_instance + attr_reader :transport - save_existing + def mark_persisted! + @new_record = false end - def save_new - response = @transport.post(url: "#{@url}?expand=true", params: @attributes) - return safe_json_parse(response.body) if response.status == 201 + def load_response!(response) + @attributes = frozen_attributes(response.decoded(:object)) + @baseline = @attributes + @new_record = false + end - save_error(response) + def raise_if_new!(operation) + raise Error, "#{self.class.name} has not been saved, so there is nothing to #{operation}" if new_record? end - def save_existing - attributes_to_post = {} - @changes.each do |name, values| - attributes_to_post[name] = values[1] - end - response = @transport.put(url: "#{@url}/#{@attributes[:id]}?expand=true", params: attributes_to_post) - return safe_json_parse(response.body) if response.status == 200 + def writable_attributes? = true - save_error(response) - end + def write_attribute(key, value) + raise Error, "#{self.class.name}#id cannot be changed: it is what addresses this record" if key == :id - def save_error(response) - raise ResponseError.from(response, operation: 'save object', resource_class: self.class) + staged = frozen_attributes(value) + @attributes = @attributes.merge(key => staged).freeze + staged end - def symbolize_keys_deep!(hash) - hash.keys.each do |key| - key_symbol = key.respond_to?(:to_sym) ? key.to_sym : key - hash[key_symbol] = hash.delete key # Preserve order even when key == key_symbol + def member_path = self.class.member_path(require_id!) - symbolize_keys_deep! hash[key_symbol] if hash[key_symbol].is_a? Hash - end + def require_id! + id || raise(Error, "#{self.class.name} has no id, save it first") end end end diff --git a/lib/zammad_api/resources/group.rb b/lib/zammad_api/resources/group.rb index 3a6a768c..7c61bcb5 100644 --- a/lib/zammad_api/resources/group.rb +++ b/lib/zammad_api/resources/group.rb @@ -1,3 +1,13 @@ -class ZammadAPI::Resources::Group < ZammadAPI::Resources::Base - url '/api/v1/groups' +# frozen_string_literal: true + +module ZammadAPI + module Resources + # A group: what a ticket is assigned to, and what agents are given access by. + # Reached through {Client#groups}. + class Group < Base + path 'api/v1/groups' + + searchable true + end + end end diff --git a/lib/zammad_api/resources/organization.rb b/lib/zammad_api/resources/organization.rb index 671939f6..5bb80dbe 100644 --- a/lib/zammad_api/resources/organization.rb +++ b/lib/zammad_api/resources/organization.rb @@ -1,3 +1,13 @@ -class ZammadAPI::Resources::Organization < ZammadAPI::Resources::Base - url '/api/v1/organizations' +# frozen_string_literal: true + +module ZammadAPI + module Resources + # An organization that customers belong to. Reached through + # {Client#organizations}. + class Organization < Base + path 'api/v1/organizations' + + searchable true + end + end end diff --git a/lib/zammad_api/resources/ticket.rb b/lib/zammad_api/resources/ticket.rb index 448209b0..b0cc4ee4 100644 --- a/lib/zammad_api/resources/ticket.rb +++ b/lib/zammad_api/resources/ticket.rb @@ -1,25 +1,48 @@ -class ZammadAPI::Resources::Ticket < ZammadAPI::Resources::Base - url '/api/v1/tickets' +# frozen_string_literal: true - def articles - response = @transport.get(url: "/api/v1/ticket_articles/by_ticket/#{id}?expand=true") - if response.status != 200 - raise ZammadAPI::ResponseError.from(response, operation: 'get articles', resource_class: self.class) - end +module ZammadAPI + module Resources + # A ticket. Reached through {Client#tickets}, and its articles through + # {#articles} and {#add_article}. + class Ticket < Base + path 'api/v1/tickets' - data = safe_json_parse(response.body) + # TicketsController#index hardcodes `reorder(id: :asc)`, so it reads nothing + # but the paging - not even sort_by. + sortable false - data.collect do |raw| - item = ZammadAPI::Resources::TicketArticle.new(@transport, raw) - item.new_instance = false - item - end - end + # /api/v1/tickets caps the page size at 100, unlike the generic index + # endpoints, see TicketsController#index. + max_per_page 100 + + searchable true - def article(data) - data[:ticket_id] = @attributes[:id] - item = ZammadAPI::Resources::TicketArticle.new(@transport, data) - item.save - item + # Every article of this ticket, read in one request on each call. + # + # @return [Array] + # @raise [Error] when the ticket has no id yet + # @raise [ResponseError] when Zammad rejected the request + def articles + path = "#{TicketArticle.resource_path}/by_ticket/#{Transport.escape_path_segment(require_id!)}" + response = transport.get(path, query: { expand: true }) + + response.decoded(:array).map { TicketArticle.from_response(transport, it) } + end + + # Adds an article to this ticket. + # + # @example + # ticket.add_article(subject: 'Update', body: 'Reset link sent.', type: 'note') + # + # @param attributes [Hash] article attributes, e.g. +body:+, +type:+ + # @return [TicketArticle] the created article + # @raise [Error] when the ticket has no id yet + # @raise [ResponseError] when Zammad rejected the request + def add_article(attributes = {}) + record = TicketArticle.new(transport, Hash(attributes).merge(ticket_id: require_id!)) + record.save! + record + end + end end end diff --git a/lib/zammad_api/resources/ticket_article.rb b/lib/zammad_api/resources/ticket_article.rb index 890918bf..7d5d4160 100644 --- a/lib/zammad_api/resources/ticket_article.rb +++ b/lib/zammad_api/resources/ticket_article.rb @@ -1,11 +1,18 @@ -class ZammadAPI::Resources::TicketArticle < ZammadAPI::Resources::Base - url '/api/v1/ticket_articles' +# frozen_string_literal: true - def attachments - @attributes[:attachments].collect do |raw| - raw[:ticket_id] = @attributes[:ticket_id] - raw[:article_id] = @attributes[:id] - ZammadAPI::Resources::TicketArticleAttachment.new(@transport, raw) +module ZammadAPI + module Resources + # An article of a ticket: an e-mail, a note, a phone call. Reached through + # {Ticket#articles}, or by id through {Client#ticket_articles}. + class TicketArticle < Base + path 'api/v1/ticket_articles' + + # @return [Array] the article's attachments + def attachments + (attributes[:attachments] || []).map do |raw| + TicketArticleAttachment.new(transport, raw.merge(ticket_id: attributes[:ticket_id], article_id: id)) + end + end end end end diff --git a/lib/zammad_api/resources/ticket_article_attachment.rb b/lib/zammad_api/resources/ticket_article_attachment.rb index c3e06d90..cd260e87 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -1,18 +1,34 @@ -class ZammadAPI::Resources::TicketArticleAttachment < ZammadAPI::Resources::Base - def initialize(transport, attributes = {}) # rubocop:disable Lint/MissingSuper - @transport = transport - @attributes = attributes - symbolize_keys_deep!(@attributes) - end +# frozen_string_literal: true - def method_missing(method, *_args) - @attributes[method.to_sym] - end +module ZammadAPI + module Resources + # An attachment of a ticket article. + # + # Attachments are read-only metadata until {#download} is called, which + # returns the file contents. + class TicketArticleAttachment + include AttributeAccess + + # @api private + # @param transport [Transport] + # @param attributes [Hash] + def initialize(transport, attributes = {}) + @transport = transport + @attributes = frozen_attributes(Hash(attributes)) # steep:ignore UnresolvedOverloading + end - def download - response = @transport.get(url: "/api/v1/ticket_attachment/#{ticket_id}/#{article_id}/#{id}") - return response.body if response.status == 200 + # Downloads the attachment. + # + # @return [String] the file contents, in +ASCII-8BIT+ encoding + # @raise [ResponseError] when Zammad rejected the request + def download + segments = %i[ticket_id article_id id].map { Transport.escape_path_segment(fetch(it)) } + @transport.get("api/v1/ticket_attachment/#{segments.join('/')}").raw_body.b + end - raise ZammadAPI::ResponseError.from(response, operation: 'get articles', resource_class: self.class) + def inspect + "#<#{self.class.name} id=#{id.inspect} filename=#{self[:filename].inspect} size=#{self[:size].inspect}>" + end + end end end diff --git a/lib/zammad_api/resources/ticket_priority.rb b/lib/zammad_api/resources/ticket_priority.rb index c46534a2..1d2910e7 100644 --- a/lib/zammad_api/resources/ticket_priority.rb +++ b/lib/zammad_api/resources/ticket_priority.rb @@ -1,3 +1,11 @@ -class ZammadAPI::Resources::TicketPriority < ZammadAPI::Resources::Base - url '/api/v1/ticket_priorities' +# frozen_string_literal: true + +module ZammadAPI + module Resources + # A ticket priority, such as "2 normal". Reached through + # {Client#ticket_priorities}. + class TicketPriority < Base + path 'api/v1/ticket_priorities' + end + end end diff --git a/lib/zammad_api/resources/ticket_state.rb b/lib/zammad_api/resources/ticket_state.rb index d05b75f9..67c6e030 100644 --- a/lib/zammad_api/resources/ticket_state.rb +++ b/lib/zammad_api/resources/ticket_state.rb @@ -1,3 +1,10 @@ -class ZammadAPI::Resources::TicketState < ZammadAPI::Resources::Base - url '/api/v1/ticket_states' +# frozen_string_literal: true + +module ZammadAPI + module Resources + # A ticket state, such as "open". Reached through {Client#ticket_states}. + class TicketState < Base + path 'api/v1/ticket_states' + end + end end diff --git a/lib/zammad_api/resources/user.rb b/lib/zammad_api/resources/user.rb index c5c667a3..46329059 100644 --- a/lib/zammad_api/resources/user.rb +++ b/lib/zammad_api/resources/user.rb @@ -1,3 +1,17 @@ -class ZammadAPI::Resources::User < ZammadAPI::Resources::Base - url '/api/v1/users' +# frozen_string_literal: true + +module ZammadAPI + module Resources + # A user: a customer, an agent or an administrator. Reached through + # {Client#users}, and the one the client authenticates as through {Client#me}. + class User < Base + path 'api/v1/users' + + # UsersController#index hardcodes `reorder(id: :asc)`, so it reads nothing + # but the paging - not even sort_by. + sortable false + + searchable true + end + end end diff --git a/lib/zammad_api/response.rb b/lib/zammad_api/response.rb new file mode 100644 index 00000000..b74aa725 --- /dev/null +++ b/lib/zammad_api/response.rb @@ -0,0 +1,52 @@ +# frozen_string_literal: true + +require 'json' + +module ZammadAPI + # A decoded HTTP response. + # + # This deliberately does not expose Faraday objects, so that the HTTP client + # stays an implementation detail of {Transport}. + # + # @!attribute [r] status + # @return [Integer] HTTP status code + # @!attribute [r] headers + # @return [Hash{String => String}] response headers, keys downcased + # @!attribute [r] body + # @return [Hash, Array, String] JSON responses are decoded with symbol + # keys; every other content type is left as the raw body + # @!attribute [r] raw_body + # @return [String] the undecoded response body + Response = Data.define(:status, :headers, :body, :raw_body) + + class Response + # @return [Boolean] whether the status code is in the 2xx range + def success? = status.between?(200, 299) + + # Decodes a JSON body with symbol keys. Anything else - a proxy error page, + # a file download, a body that does not parse - is handed back as it is. + # + # @api private + # @param content_type [String, nil] + # @param raw_body [String] + # @return [Hash, Array, String] + def self.decode_body(content_type, raw_body) + return raw_body if !content_type.to_s.include?('json') || raw_body.empty? + + JSON.parse(raw_body, symbolize_names: true) + rescue JSON::ParserError + raw_body + end + + # The body, checked to be the JSON object or array the caller expects. + # + # @param shape [:object, :array] + # @return [Hash, Array] + # @raise [ParseError] when the body has another shape + def decoded(shape) + return body if body.is_a?(shape == :object ? Hash : Array) + + raise ParseError, "expected a JSON #{shape}, got #{body.class}" + end + end +end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 5ade3333..20d65802 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1,63 +1,235 @@ +# frozen_string_literal: true + require 'faraday' -require 'openssl' +require 'faraday/retry' +require 'uri' module ZammadAPI + # Performs the HTTP requests against a Zammad instance. + # + # Instances are immutable once built: {#with_on_behalf_of} returns a copy + # rather than mutating shared state, which makes a single transport safe to + # use from several threads. + # + # @api private class Transport - attr_accessor :url, :user, :password, :on_behalf_of - - def initialize(config, logger) - @logger = logger - @logger.debug "Transport to #{config[:url]} with #{config[:user]}:#{config[:password]}" - @conn = Faraday.new(url: config[:url]) do |faraday| - #faraday.request :url_encoded # form-encode POST params - #faraday.response :logger # log requests to STDOUT - faraday.adapter Faraday.default_adapter # make requests with Net::HTTP + # The method that is retried: the one that only reads. A write that timed + # out may still have been applied, so it is not sent twice. + RETRIABLE_METHODS = %i[get].freeze + + # Statuses a read is retried on. + RETRIABLE_STATUSES = [429, 500, 502, 503, 504].freeze + + # Errors a read is retried on. The adapter wraps socket and TLS errors + # into Faraday's own classes. + RETRIABLE_EXCEPTIONS = [Faraday::RetriableResponse, Faraday::ConnectionFailed, Faraday::TimeoutError].freeze + + # Keys whose values are never written to the log. Matched anywhere in the + # name, as Zammad's own log filter does, so +monkey_id+ is hidden too. + SENSITIVE_KEY_PATTERN = /passw|pwd|bind_pw|passphrase|secret|token|credential|cookie|authorization|key|otp|salt/i + + # A path that opens with a scheme, which Faraday would send to that host. + ABSOLUTE_URL = /\A[a-z][a-z0-9+.-]*:/i + private_constant :ABSOLUTE_URL + + # @return [Config] + attr_reader :config + + # @return [String, nil] the user requests are performed for, sent as the + # +From+ header + attr_reader :on_behalf_of + + # A record id as a path segment, percent-encoded. + # + # @param value [Integer, String] + # @return [String] + # @raise [ArgumentError] for an id that is nil or empty + def self.escape_path_segment(value) + segment = value.to_s + raise ArgumentError, 'a record id is required' if segment.empty? + + URI.encode_uri_component(segment) + end + + # A request path relative to the instance URL. A leading slash is + # dropped, so paths can be pasted from the Zammad documentation. + # + # @param path [String] + # @return [String] + # @raise [ArgumentError] for an absolute URL, which would carry this + # client's credentials to another host + def self.relative_path(path) + relative = path.to_s.sub(%r{\A/+}, '') + if ABSOLUTE_URL.match?(relative) + raise ArgumentError, "a request path is relative to the instance URL, and this one is an absolute URL: pass the path alone, such as 'api/v1/tickets'" end - @conn.headers[:user_agent] = 'Zammad API Ruby' - if config[:http_token] && !config[:http_token].empty? - @conn.request :authorization, 'Token', config[:http_token] - elsif config[:oauth2_token] && !config[:oauth2_token].empty? - @conn.request :authorization, 'Bearer', config[:oauth2_token] - else - @conn.request :authorization, :basic, config[:user], config[:password] + + relative + end + + # A path as it may be logged or named in an error: without a query string + # or fragment, which may carry a token. + # + # @param path [String] + # @return [String] + def self.redact_path(path) = path.to_s.sub(/[?#].*/m, '') + + # Replaces the values of sensitive keys, at any depth, for the log. + # + # @param value [Object] + # @return [Object] + def self.redact(value) + case value + when Hash then value.to_h { |key, nested| [key, SENSITIVE_KEY_PATTERN.match?(key.to_s) ? Config::REDACTION : redact(nested)] } + when Array then value.map { redact(it) } + else value end end - %w[get post put delete].each do |method| - class_eval <<-RUBY, __FILE__, __LINE__ + 1 - def #{method}(params) # def get(params) - run_request(:#{method}, params) # run_request(:get, params) - end # end - RUBY + # @param config [Config] + # @param on_behalf_of [String, nil] see {Client#on_behalf_of} + # @raise [ConfigurationError] when the connection cannot be built + def initialize(config, on_behalf_of: nil) + @config = config + @on_behalf_of = on_behalf_of + @connection = build_connection + end + + # @param identifier [String, nil] see {Client#on_behalf_of} + # @return [Transport] a copy that performs requests for that user + def with_on_behalf_of(identifier) + copy = dup + copy.instance_variable_set(:@on_behalf_of, identifier) + copy + end + + # @param config [Config] + # @return [Transport] a new transport for +config+, for the same user + def with_config(config) = self.class.new(config, on_behalf_of: on_behalf_of) + + def inspect + "#<#{self.class.name} url=#{config.url.inspect} auth=#{config.authentication_scheme}#{" on_behalf_of=#{on_behalf_of.inspect}" if on_behalf_of}>" + end + + # Performs a request and raises on anything but a 2xx response. + # + # @param method [Symbol] +:get+, +:post+, +:put+ or +:delete+ + # @param path [String] path relative to {Config#url} + # @param query [Hash, nil] query string parameters + # @param body [Hash, Array, String, nil] request payload; a Hash or Array + # is encoded as JSON, a String is sent as it is + # @param headers [Hash, nil] request headers + # @return [Response] + # @raise [ResponseError] for non-2xx responses + # @raise [TimeoutError] when the response took longer than {Config#timeout} + # @raise [ConnectionError] when the instance was unreachable, including + # a connection not opened within {Config#open_timeout} + def request(method, path, query: nil, body: nil, headers: nil) + path = Transport.relative_path(path) + request_line = "#{method.to_s.upcase} #{Transport.redact_path(path)}" + log_request(request_line, query, body, headers) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + response = decode(perform(method, path, query, body, headers)) + log_response(request_line, response, started) + return response if response.success? + + raise ResponseError.build(response, request_line) + rescue Faraday::TimeoutError => e + raise TimeoutError, "#{request_line} timed out (#{e.message})" + rescue Faraday::SSLError => e + raise ConnectionError, "#{request_line} failed: TLS handshake with #{config.url} failed (#{e.message})" + rescue Faraday::ConnectionFailed => e + raise ConnectionError, "#{request_line} failed: #{config.url} is unreachable (#{e.message})" end + # The verb shorthands. + def get(path, **options) = request(:get, path, **options) + def post(path, **options) = request(:post, path, **options) + def put(path, **options) = request(:put, path, **options) + def delete(path, **options) = request(:delete, path, **options) + private - def run_request(verb, param) - @logger.debug "#{verb.to_s.upcase}: #{@url}#{param[:url]}" + # The connection's :json middleware encodes a Hash or Array body. + def perform(method, path, query, body, headers) + @connection.public_send(method, path) do |request| + request.params.update(query) if query + headers&.each { |name, value| request.headers[name.to_s] = value.to_s } + request.headers['From'] = on_behalf_of if on_behalf_of + request.body = body if body + end + end - with_params = !param[:params].nil? - if with_params - @logger.debug "Params: #{param[:params].inspect}" + def build_connection + Faraday.new( + url: config.url, + ssl: { verify: config.ssl_verify }, + proxy: config.proxy, + request: { timeout: config.timeout, open_timeout: config.open_timeout }, + headers: { 'User-Agent' => config.user_agent, 'Accept' => 'application/json' } + ) do |faraday| + apply_authentication(faraday) + faraday.request :json + faraday.request :retry, retry_options + faraday.adapter(config.adapter) if config.adapter + config.middleware&.call(faraday) end + rescue Faraday::Error => e + raise ConfigurationError, "config could not be used to build a connection: #{e.message}" + end - response = @conn.public_send(verb) do |req| - req.url param[:url] + def retry_options + { + max: config.retries, + interval: config.retry_interval, + max_interval: config.timeout, + interval_randomness: 0.5, + backoff_factor: 2, + retry_statuses: RETRIABLE_STATUSES, + methods: RETRIABLE_METHODS, + exceptions: RETRIABLE_EXCEPTIONS + } + end - if with_params - req.headers['Content-Type'] = 'application/json' - req.body = param[:params].to_json - end + def apply_authentication(faraday) + case config.authentication_scheme + when :http_token then faraday.request :authorization, 'Token', config.http_token + when :oauth2_token then faraday.request :authorization, 'Bearer', config.oauth2_token + else faraday.request :authorization, :basic, config.user, config.password + end + end - if !on_behalf_of.nil? - req.headers['From'] = on_behalf_of - end + def decode(faraday_response) + headers = faraday_response.headers.to_h.to_h { |name, value| [name.to_s.downcase, value.to_s] }.freeze + raw_body = faraday_response.body.to_s - yield(req) if block_given? + Response.new( + status: faraday_response.status, + headers: headers, + body: Response.decode_body(headers['content-type'], raw_body), + raw_body: raw_body + ) + end + + def log_request(request_line, query, body, headers) + logger.debug do + "Zammad API request: #{request_line}#{" query=#{Transport.redact(query).inspect}" if query}#{" headers=#{Transport.redact(headers).inspect}" if headers}" end + logger.debug { "Zammad API payload: #{loggable_body(body)}" } if body + end - @logger.debug "Response: #{response.body}" - response + def log_response(request_line, response, started) + duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round + logger.debug { "Zammad API response: #{request_line} -> #{response.status} in #{duration}ms" } end + + def loggable_body(body) + return Transport.redact(body).inspect if body.is_a?(Hash) || body.is_a?(Array) + + "[#{body.to_s.bytesize} bytes, not logged]" + end + + def logger = config.logger end end diff --git a/lib/zammad_api/version.rb b/lib/zammad_api/version.rb index 4915c541..2bcc0743 100644 --- a/lib/zammad_api/version.rb +++ b/lib/zammad_api/version.rb @@ -1,3 +1,6 @@ +# frozen_string_literal: true + module ZammadAPI - VERSION = '1.4.0'.freeze + # The version of this gem. {Client#version} is the Zammad instance's. + VERSION = '2.0.0.alpha1' end diff --git a/spec/integration/zammad_api_spec.rb b/spec/integration/zammad_api_spec.rb new file mode 100644 index 00000000..79961e3d --- /dev/null +++ b/spec/integration/zammad_api_spec.rb @@ -0,0 +1,288 @@ +# frozen_string_literal: true + +# Drives the Zammad that TEST_URL names, as its administrator. +# +# Each example makes the records it needs under a name of its own and +# destroys them afterwards, and none asserts on what else the instance +# holds, so the suite passes against the same Zammad as often as it is run. +RSpec.describe ZammadAPI do + let(:client) { LiveZammad.client } + let(:suffix) { SecureRandom.hex(4) } + let(:made) { [] } + + after { made.reverse_each(&:destroy) } + + def create_group(**attributes) + client.groups.create(name: "spec-#{suffix}", **attributes).tap { made << it } + end + + def create_ticket + client.tickets.create( + title: "spec ticket #{suffix}", + group: 'Users', + customer: LiveZammad.login, + article: { subject: 'first', body: 'created by the integration specs', type: 'note' } + ).tap { made << it } + end + + describe 'signing in' do + it 'reads the account the credentials belong to' do + expect(client.me.login).to eq(LiveZammad.login) + end + + it 'reads the version of the instance' do + expect(client.version).to match(/\A\d+\.\d+/) + end + + it 'accepts an access token' do + name = "spec-#{suffix}" + token = client.post('api/v1/user_access_token', body: { name: name, permission: ['ticket.agent'] }).body.fetch(:token) + + expect(described_class::Client.new(url: LiveZammad.url, http_token: token).me.login).to eq(LiveZammad.login) + ensure + id = client.get('api/v1/user_access_token').body.fetch(:tokens).find { it[:name] == name }&.fetch(:id) + client.delete("api/v1/user_access_token/#{id}") if id + end + + it 'refuses credentials that are wrong' do + stranger = LiveZammad.client(user: 'nobody', password: 'wrong') + + expect { stranger.me }.to raise_error(ZammadAPI::AuthenticationError) { expect(it.status).to eq(401) } + end + end + + describe 'every resource' do + described_class::Client::RESOURCES.each do |name, resource_class| + it "lists and finds #{name}" do + create_ticket if %i[tickets ticket_articles].include?(name) + first = client.resource(name).first + + expect(first).to be_a(resource_class) + expect(client.resource(name).find(first.id)).to eq(first) + end + end + end + + describe 'a record' do + it 'is created and found again' do + group = create_group(note: 'first') + + expect(client.groups.find(group.id)).to have_attributes(name: "spec-#{suffix}", note: 'first') + end + + it 'saves only what changed' do + group = create_group(note: 'first') + group.note = 'second' + + expect(group.changes).to eq(note: %w[first second]) + expect(group.save).to be(true) + expect(client.groups.find(group.id)).to have_attributes(name: group.name, note: 'second') + end + + it 'is updated in one call' do + group = create_group + group.update!(note: 'updated') + + expect(client.groups.find(group.id).note).to eq('updated') + end + + it 'drops unsaved changes on reload' do + group = create_group(note: 'first') + group.note = 'unsaved' + + expect(group.reload).to have_attributes(note: 'first', changed?: false) + end + + it 'reports a save Zammad rejects, and raises from save!' do + organization = client.organizations.new(name: '') + + expect(organization.save).to be(false) + expect(organization.error).to be_a(ZammadAPI::ValidationError) + expect { organization.save! }.to raise_error(ZammadAPI::ValidationError) + end + + it 'is destroyed' do + group = client.groups.create(name: "spec-#{suffix}") + + expect(group.destroy).to be(true) + expect(group).to be_destroyed + expect(client.groups.exists?(group.id)).to be(false) + end + + it 'is destroyed by its id' do + user = client.users.create(firstname: 'Spec', lastname: suffix, email: "spec-#{suffix}@example.com") + organization = client.organizations.create(name: "spec-#{suffix}") + + expect(client.users.destroy(user.id)).to be(true) + expect(client.organizations.destroy(organization.id)).to be(true) + expect([client.users.exists?(user.id), client.organizations.exists?(organization.id)]).to eq([false, false]) + end + + it 'is a NotFoundError where there is none' do + expect { client.groups.find(0) }.to raise_error(ZammadAPI::NotFoundError, %r{\AGET api/v1/groups/0 failed: }) + end + end + + describe 'a collection' do + let!(:groups) { %w[a b].map { create_group(name: "spec-#{suffix}-#{it}") } } + + it 'walks every page' do + ids = [] + client.groups.in_batches(of: 1) { |page| ids.concat(page.map(&:id)) } + + expect(ids).to eq(client.groups.pluck(:id)).and include(*groups.map(&:id)) + end + + it 'yields record by record' do + expect(client.groups.find_each(batch_size: 1).map(&:id)).to eq(client.groups.pluck(:id)) + end + + it 'reads one page' do + first, second = [1, 2].map { client.groups.page(it, per_page: 1).to_a } + + expect([first.size, second.size]).to eq([1, 1]) + expect(first).not_to eq(second) + end + + it 'reads the first records' do + expect(client.groups.first(2).size).to eq(2) + end + + it 'sorts on the server' do + names = groups.map(&:name) + + expect(client.groups.order(:name).pluck(:name) & names).to eq(names) + expect(client.groups.order(name: :desc).pluck(:name) & names).to eq(names.reverse) + end + end + + describe 'a search' do + it 'finds the account it is signed in as' do + expect(client.users.search(LiveZammad.login).map(&:login)).to include(LiveZammad.login) + end + + it 'finds tickets' do + create_ticket + + expect(client.tickets.search('*').first).to be_a(ZammadAPI::Resources::Ticket) + end + + it 'counts its hits' do + create_ticket + tickets = client.tickets.search('*') + + expect(tickets.count).to eq(tickets.to_a.size).and be_positive + end + + # A search is served newest first unless it is told otherwise. + it 'sorts its hits' do + 2.times { create_ticket } + ids = client.tickets.search('*').order(:id).first(2).map(&:id) + + expect(ids.size).to eq(2) + expect(ids).to eq(ids.sort) + end + + it 'is empty where nothing matches' do + expect(client.groups.search("no-such-group-#{suffix}")).to be_empty + end + end + + describe 'find_by' do + it 'walks a resource that has no search' do + expect(client.ticket_states.find_by(name: 'new')).to have_attributes(name: 'new') + end + + it 'searches where it can, and compares every value' do + me = client.me + + expect(client.users.find_by(login: me.login, email: me.email)).to eq(me) + end + + it 'answers nil, and find_by! raises, where nothing matches' do + expect(client.groups.find_by(name: "no-such-group-#{suffix}")).to be_nil + expect { client.groups.find_by!(name: "no-such-group-#{suffix}") }.to raise_error(ZammadAPI::NotFoundError) + end + end + + describe 'a ticket' do + let(:ticket) { create_ticket } + + it 'is created with its first article' do + expect(ticket.number).not_to be_nil + expect(ticket.articles.map(&:body)).to eq(['created by the integration specs']) + end + + it 'takes another article' do + article = ticket.add_article(subject: 'second', body: 'another one', type: 'note') + + expect(ticket.articles.map(&:id)).to eq([ticket.articles.first.id, article.id]) + end + + it 'carries a file there and back' do + ticket.add_article( + body: 'see attachment', + type: 'note', + attachments: [{ filename: 'hello.txt', data: ['hello world'].pack('m0'), 'mime-type': 'text/plain' }] + ) + attachment = ticket.articles.last.attachments.first + + expect(attachment.filename).to eq('hello.txt') + expect(attachment.download).to eq('hello world') + end + + it 'is closed by an update' do + expect(ticket.update(state: 'closed')).to be(true) + expect(client.tickets.find(ticket.id).state).to eq('closed') + end + end + + describe 'acting on behalf of a user' do + it 'reads as that user' do + ticket = create_ticket + + expect(client.on_behalf_of(LiveZammad.login) { it.tickets.find(ticket.id) }).to eq(ticket) + end + + # Acting for the account the client is signed in as reads the same with + # the header as without. A user Zammad does not know is refused, which is + # the answer that says the header arrived. + it 'is refused for a user Zammad does not know' do + stranger = client.on_behalf_of("nobody-#{suffix}@example.com") + + expect { stranger.groups.first }.to raise_error(ZammadAPI::AuthorizationError) + end + end + + describe 'a raw request' do + it 'reads, writes and deletes by query' do + tag = { object: 'Ticket', o_id: create_ticket.id, item: 'integration-spec' } + tags = -> { client.get('api/v1/tags', query: tag.slice(:object, :o_id)).body } + + client.post('api/v1/tags/add', query: tag) + expect(tags.call).to eq(tags: ['integration-spec']) + + client.delete('api/v1/tags/remove', query: tag) + expect(tags.call).to eq(tags: []) + end + + it 'sends a body' do + group = create_group + response = client.put("api/v1/groups/#{group.id}", body: { note: 'raw' }) + + expect(response.status).to eq(200) + expect(response.body).to include(id: group.id, note: 'raw') + end + end + + describe 'a resource of your own' do + let(:role_class) { Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' } } + + it 'is listed and found like the modelled ones' do + roles = client.resource(role_class) + + expect(roles.pluck(:name)).to include('Admin', 'Agent', 'Customer') + expect(roles.find_by(name: 'Agent')).to be_a(role_class) + end + end +end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6c318c4a..c6480230 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,50 +1,56 @@ -$LOAD_PATH.unshift File.expand_path('../lib', __dir__) - -# we don't require 'webmock/rspec' over here -# since we want to mock only certain requests -# but the API should be available in general -require 'webmock' - -RSpec.configure do |config| - config.include WebMock::API - config.include WebMock::Matchers +# frozen_string_literal: true + +if ENV['COVERAGE'] + require 'simplecov' + SimpleCov.start do + enable_coverage :branch + skip '/spec/' + minimum_coverage line: 90, branch: 75 + end end -require 'zammad_api' +$LOAD_PATH.unshift File.expand_path('../lib', __dir__) -class Helper - def self.config - { - url: ENV['TEST_URL'] || 'http://localhost:3000/', - user: ENV['TEST_USER'] || 'admin@example.com', - password: ENV['TEST_PASSWORD'] || 'test' - } - end +# Unit specs run entirely against stubs; integration specs opt back out below. +require 'webmock/rspec' +require 'zammad_api' - def self.client(params = {}) - ZammadAPI::Client.new( - url: params[:url] || config[:url], - user: params[:user] || config[:user], - password: params[:password] || config[:password], - ) - end +Dir[File.expand_path('support/**/*.rb', __dir__)].each { require it } - # start auto wizard - def self.auto_wizard - conn = Faraday.new(url: config[:url]) do |faraday| - faraday.adapter Faraday.default_adapter # make requests with Net::HTTP +RSpec.configure do |config| + config.include ClientHelper + + config.expect_with(:rspec) { it.syntax = :expect } + config.mock_with(:rspec) { it.verify_partial_doubles = true } + + config.disable_monkey_patching! + config.filter_run_when_matching :focus + config.example_status_persistence_file_path = 'tmp/rspec_status.txt' + + # Unit specs run against WebMock stubs and never touch the network. + # Integration specs need a live Zammad and write to it, so they run only + # where TEST_URL names one. Without it they are left out, and said to be, + # so that a bare `rspec` is the unit specs; a run that selected nothing + # else fails rather than passing with no examples. + config.define_derived_metadata(file_path: %r{/spec/integration/}) { it[:integration] = true } + config.fail_if_no_examples = true + + if LiveZammad.url.nil? + config.filter_run_excluding :integration + config.when_first_matching_example_defined(:integration) do + warn 'Integration specs left out: they create and delete records, so they run only against the Zammad that ' \ + 'TEST_URL names. Set TEST_URL, TEST_USER and TEST_PASSWORD to run them.' end - - url_auto_wizard = '/api/v1/getting_started/auto_wizard' - response = conn.get url_auto_wizard - data = JSON.parse(response.body) - - return true if data['auto_wizard_success'] - - raise "Unable to start auto wizard: #{response.body}" end - def self.random - rand(99_999_999).to_s + # They need the real network, so WebMock steps aside for them. + config.around(:each, :integration) do |example| + WebMock.allow_net_connect! + WebMock.disable! + LiveZammad.set_up! + example.run + ensure + WebMock.enable! + WebMock.disable_net_connect! end end diff --git a/spec/support/client_helper.rb b/spec/support/client_helper.rb new file mode 100644 index 00000000..51110dd5 --- /dev/null +++ b/spec/support/client_helper.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +# Helpers for unit specs, which talk to WebMock stubs instead of a Zammad. +module ClientHelper + BASE_URL = 'http://zammad.test/' + + # Retries are disabled by default so that specs exercising error paths do + # not wait for the backoff intervals. + def unit_config(**overrides) + { url: BASE_URL, http_token: 'test-token', retries: 0 }.merge(overrides) + end + + def unit_client(**overrides) + ZammadAPI::Client.new(**unit_config(**overrides)) + end + + def unit_transport(**overrides) + ZammadAPI::Transport.new(ZammadAPI::Config.new(**unit_config(**overrides))) + end + + # @return [Hash] arguments for WebMock's +to_return+ with a JSON body + def json_response(body, status: 200, headers: {}) + { + status: status, + body: JSON.generate(body), + headers: { 'Content-Type' => 'application/json' }.merge(headers) + } + end +end diff --git a/spec/support/integration_helper.rb b/spec/support/integration_helper.rb new file mode 100644 index 00000000..73e3e086 --- /dev/null +++ b/spec/support/integration_helper.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +require 'securerandom' + +# The Zammad the integration specs run against: the one TEST_URL names. +# +# There is no default. The specs create and delete records, and +# `http://localhost:3000/` is where a Zammad under development listens. +module LiveZammad + module_function + + # @return [String, nil] nil where TEST_URL is not set + def url + value = ENV['TEST_URL'].to_s.strip + value.empty? ? nil : value + end + + def login = ENV.fetch('TEST_USER', 'admin@example.com') + def password = ENV.fetch('TEST_PASSWORD', 'test') + + # @return [ZammadAPI::Client] signed in as the administrator, unless the + # options say otherwise + def client(**options) + ZammadAPI::Client.new(url: url, user: login, password: password, **options) + end + + # A freshly booted Zammad has no administrator until its auto wizard has + # run. Asked for once; an instance that is set up already does nothing. + def set_up! + @set_up ||= Faraday.new(url: url, request: { open_timeout: 10, timeout: 60 }).get('api/v1/getting_started/auto_wizard') && true + end +end diff --git a/spec/support/strong_parameters.rb b/spec/support/strong_parameters.rb new file mode 100644 index 00000000..ee231654 --- /dev/null +++ b/spec/support/strong_parameters.rb @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +# What permitted `ActionController::Parameters` are to this gem, without +# Rails: not a Hash, and converting to one with String keys through `to_hash`, +# all the way down. +class StrongParameters + def initialize(**values) + @values = values + end + + def to_hash + @values.to_h { |key, value| [key.to_s, value.is_a?(self.class) ? value.to_hash : value] } + end +end diff --git a/spec/unit/zammad_api/attribute_access_spec.rb b/spec/unit/zammad_api/attribute_access_spec.rb new file mode 100644 index 00000000..b6b7c316 --- /dev/null +++ b/spec/unit/zammad_api/attribute_access_spec.rb @@ -0,0 +1,243 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::AttributeAccess do + subject(:record) { record_class.new(attributes) } + + let(:record_class) do + Class.new do + include ZammadAPI::AttributeAccess + + def initialize(attributes) + @attributes = frozen_attributes(attributes) + end + end + end + + let(:attributes) do + { + 'id' => 1, + 'name' => 'Support', + 'preferences' => { 'notes' => [{ 'body' => 'hello' }] } + } + end + + describe 'key normalization' do + it 'symbolizes top level keys' do + expect(record.attributes.keys).to eq(%i[id name preferences]) + end + + it 'symbolizes nested hash keys' do + expect(record.attributes[:preferences].keys).to eq([:notes]) + end + + it 'symbolizes hash keys inside arrays' do + expect(record.attributes[:preferences][:notes].first).to eq({ body: 'hello' }) + end + + it 'leaves keys alone that cannot become symbols' do + expect(record_class.new(1 => 'one').attributes).to eq(1 => 'one') + end + end + + describe 'reading' do + it 'reads through a reader method' do + expect(record.name).to eq('Support') + end + + it 'reads through #[]' do + expect(record[:name]).to eq('Support') + end + + it 'accepts a string key in #[]' do + expect(record['name']).to eq('Support') + end + + it 'exposes the id' do + expect(record.id).to eq(1) + end + + it 'raises NoMethodError for an attribute the record does not carry' do + expect { record.custom_field }.to raise_error(NoMethodError, /undefined method 'custom_field'/) + end + + it 'raises NoMethodError for a reader given arguments' do + expect { record.name('Other') }.to raise_error(NoMethodError, /undefined method 'name'/) + end + + it 'still reads an attribute the record carries but Zammad left nil' do + expect(record_class.new('note' => nil).note).to be_nil + end + + it 'reports known attributes via #key?' do + expect(record.key?(:name)).to be(true) + end + + it 'returns a copy from #to_h' do + record.to_h[:name] = 'changed' + expect(record.name).to eq('Support') + end + end + + describe 'immutability' do + it 'freezes the attribute hash' do + expect { record.attributes[:name] = 'changed' }.to raise_error(FrozenError) + end + + it 'freezes a nested hash' do + expect { record.attributes[:preferences][:notes] = [] }.to raise_error(FrozenError) + end + + it 'freezes a nested array' do + expect { record.attributes[:preferences][:notes] << {} }.to raise_error(FrozenError) + end + + it 'freezes a string value' do + expect { record.name << '!' }.to raise_error(FrozenError) + end + + it 'hands out a deep copy from #to_h' do + copy = record.to_h + copy[:preferences][:notes].first[:body] = 'changed' + + expect(record.attributes[:preferences][:notes].first[:body]).to eq('hello') + end + + it 'hands out mutable strings from #to_h' do + copy = record.to_h + copy[:name] << '!' + + expect(record.name).to eq('Support') + end + end + + describe '#fetch' do + it 'returns the value for a known attribute' do + expect(record.fetch(:name)).to eq('Support') + end + + it 'raises for an unknown attribute' do + expect { record.fetch(:nope) }.to raise_error(KeyError) + end + + it 'supports a default' do + expect(record.fetch(:nope, 'fallback')).to eq('fallback') + end + + it 'supports a block' do + expect(record.fetch(:nope) { |key| "no #{key}" }).to eq('no nope') + end + end + + describe '#[]=' do + it 'goes through the same refusal a named writer does on a read-only record' do + expect { record[:note] = 'x' }.to raise_error(NoMethodError, /attributes are read-only/) + end + end + + describe 'a name that only looks like a writer' do + it 'does not invent an attribute from a comparison operator' do + # Sent rather than written as `record <= 5`, which RuboCop reads as a + # void literal and rewrites away, taking the spec with it. + expect { record.public_send(:<=, 5) }.to raise_error(NoMethodError) + + expect(record.attributes.keys).not_to include(:<) + end + + it 'is not claimed as a writer' do + expect(record).not_to respond_to(:<=) + end + end + + describe '#respond_to?' do + it 'is true for a known attribute' do + expect(record).to respond_to(:name) + end + + it 'is false for an unknown attribute' do + expect(record).not_to respond_to(:nope) + end + + it 'is false for a writer on a read-only record, which would raise' do + expect(record).not_to respond_to(:anything=) + end + + it 'is true for any writer on a record that stages changes' do + expect(ZammadAPI::Resources::Group.new(unit_transport)).to respond_to(:anything=) + end + end + + describe 'pattern matching' do + it 'matches on attribute values' do + result = case record + in { name: 'Support' } then :matched + else :not_matched + end + expect(result).to eq(:matched) + end + + it 'returns every attribute for a nil key list' do + expect(record.deconstruct_keys(nil)).to eq(record.attributes) + end + + it 'returns only the requested keys' do + expect(record.deconstruct_keys([:name])).to eq(name: 'Support') + end + end + + describe 'equality' do + it 'is the same record as another of its class carrying the same id' do + expect(record).to eq(record_class.new('id' => 1, 'name' => 'Renamed since')) + end + + it 'is not the same record as one with a different id' do + expect(record).not_to eq(record_class.new('id' => 2, 'name' => 'Support')) + end + + it 'is not the same record as one of another class with the same id' do + expect(record).not_to eq(Class.new(record_class).new('id' => 1)) + end + + it 'answers #eql? too, so a record can be a Hash key' do + expect({ record => :found }[record_class.new('id' => 1)]).to eq(:found) + end + + it 'hashes equal records alike' do + expect(record.hash).to eq(record_class.new('id' => 1).hash) + end + + context 'without an id' do + subject(:unsaved) { record_class.new('name' => 'Support') } + + it 'is still itself, so it can be found again as a Hash key' do + expect({ unsaved => :found }[unsaved]).to eq(:found) + end + + it 'is not equal to an identical record, which is still a second record' do + expect(unsaved).not_to eq(record_class.new('name' => 'Support')) + end + end + end + + describe 'serialization' do + it 'renders the attributes as a JSON object' do + expect(JSON.parse(record.to_json)) + .to eq('id' => 1, 'name' => 'Support', 'preferences' => { 'notes' => [{ 'body' => 'hello' }] }) + end + + it 'renders as its attributes when nested in a structure being generated' do + expect(JSON.parse(JSON.generate(group: record))['group']).to include('name' => 'Support') + end + + it 'carries the generator state, so pretty printing reaches the attributes' do + expect(JSON.pretty_generate(record)).to include("\n") + end + + it 'exposes the attributes to an encoder through #as_json' do + expect(record.as_json).to eq(record.to_h) + end + end + + it 'rejects writes by default' do + expect { record.name = 'other' }.to raise_error(NoMethodError, /read-only/) + end +end diff --git a/spec/unit/zammad_api/client_spec.rb b/spec/unit/zammad_api/client_spec.rb new file mode 100644 index 00000000..0a445c54 --- /dev/null +++ b/spec/unit/zammad_api/client_spec.rb @@ -0,0 +1,437 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Client do + let(:url) { "#{ClientHelper::BASE_URL}api/v1/users/1" } + + describe '.new' do + it 'accepts keyword arguments' do + expect(described_class.new(url: 'http://zammad.test/', http_token: 'token')).to be_a(described_class) + end + + it 'surfaces configuration errors' do + expect { described_class.new(http_token: 'token') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') + end + + it 'exposes the configuration' do + expect(unit_client.config).to be_a(ZammadAPI::Config) + end + end + + describe '.from_env' do + it 'reads the url and access token' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) + + config = described_class.from_env.config + expect(config.url).to eq('http://zammad.test/') + expect(config.http_token).to eq('from-env') + end + + it 'reads basic auth credentials' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_USER' => 'u', 'ZAMMAD_PASSWORD' => 'p' }) + + expect(described_class.from_env.config.authentication_scheme).to eq(:basic) + end + + it 'reads an OAuth2 token' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_OAUTH2_TOKEN' => 'oauth' }) + + expect(described_class.from_env.config.oauth2_token).to eq('oauth') + end + + it 'lets an argument win over the environment' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) + + expect(described_class.from_env(http_token: 'passed in').config.http_token).to eq('passed in') + end + + context 'when an argument names another way to authenticate' do + before do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 'from-env' }) + end + + it 'uses a user and password passed in, not the token in the environment' do + expect(described_class.from_env(user: 'u', password: 'p').config.authentication_scheme).to eq(:basic) + end + end + + it 'accepts options that have no environment variable' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't' }) + + expect(described_class.from_env(timeout: 300).config.timeout).to eq(300) + end + + it 'treats a blank variable as unset' do + stub_const('ENV', { 'ZAMMAD_URL' => 'http://zammad.test/', 'ZAMMAD_TOKEN' => 't', 'ZAMMAD_USER' => ' ' }) + + expect(described_class.from_env.config.authentication_scheme).to eq(:http_token) + end + + it 'names the variable to set when the url is missing' do + stub_const('ENV', { 'ZAMMAD_TOKEN' => 't' }) + + expect { described_class.from_env } + .to raise_error(ZammadAPI::ConfigurationError, /set ZAMMAD_URL or pass url:/) + end + end + + describe '#me' do + it 'reads the current user' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/me") + .with(query: { 'expand' => 'true' }) + .to_return(json_response({ id: 3, email: 'agent@example.com' })) + + expect(unit_client.me.email).to eq('agent@example.com') + end + end + + describe '#version' do + it 'reports the version of the Zammad instance' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/version").to_return(json_response({ version: '6.4.0' })) + + expect(unit_client.version).to eq('6.4.0') + end + + it 'is nil when the instance reports no version' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/version").to_return(json_response({})) + + expect(unit_client.version).to be_nil + end + end + + describe 'resource readers' do + ZammadAPI::Client::RESOURCES.each do |name, resource_class| + it "exposes ##{name}" do + expect(unit_client.public_send(name).resource_class).to eq(resource_class) + end + end + + it 'lists the supported resource names' do + expect(unit_client.resource_names).to eq(ZammadAPI::Client::RESOURCES.keys) + end + end + + describe 'a singular name, which the readers had in 1.x' do + it 'is a method the client does not have' do + expect { unit_client.ticket }.to raise_error(NoMethodError) + end + end + + describe '#resource' do + it 'accepts a symbol' do + expect(unit_client.resource(:groups).resource_class).to eq(ZammadAPI::Resources::Group) + end + + it 'accepts a string' do + expect(unit_client.resource('groups').resource_class).to eq(ZammadAPI::Resources::Group) + end + + it 'answers with the proxy the reader answers with' do + client = unit_client + expect(client.resource(:ticket_priorities)).to be(client.ticket_priorities) + end + + it 'raises for an unknown resource' do + expect { unit_client.resource(:unicorn) } + .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource unicorn/) + end + + context 'with a resource class a caller declared' do + let(:client) { unit_client } + let(:roles_url) { "#{ClientHelper::BASE_URL}api/v1/roles" } + + before do + stub_const('Role', Class.new(ZammadAPI::Resources::Base) { path 'api/v1/roles' }) + end + + it 'answers with a proxy for that class' do + expect(client.resource(Role).resource_class).to be(Role) + end + + it 'reads records of that class from the path it declares' do + stub_request(:get, roles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Admin' }]), json_response([])) + + expect(client.resource(Role).map { [it.class, it.name] }).to eq([[Role, 'Admin']]) + end + + it 'sends the scope of the client it was asked of' do + stub = stub_request(:get, "#{roles_url}/2") + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 2 })) + + client.on_behalf_of('agent@example.com').resource(Role).find(2) + expect(stub).to have_been_requested + end + + it 'answers a class this gem models with the proxy its reader answers with' do + expect(client.resource(ZammadAPI::Resources::Ticket)).to be(client.tickets) + end + end + end + + describe 'raw requests' do + subject(:client) { unit_client } + + let(:roles_url) { "#{ClientHelper::BASE_URL}api/v1/roles" } + + describe '#get' do + it 'reaches an endpoint the gem does not model' do + stub_request(:get, roles_url).to_return(json_response([{ id: 1, name: 'Admin' }])) + + expect(client.get('api/v1/roles').body).to eq([{ id: 1, name: 'Admin' }]) + end + + it 'returns a Response, so the status and headers stay reachable' do + stub_request(:get, roles_url).to_return(json_response([], headers: { 'X-Total-Count' => '7' })) + + response = client.get('api/v1/roles') + expect(response).to be_a(ZammadAPI::Response) + expect(response.status).to eq(200) + expect(response.headers['x-total-count']).to eq('7') + end + + it 'refuses an absolute URL whatever the case of its scheme' do + expect { client.get('HTTP://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) + end + + it 'refuses an absolute URL behind a leading slash' do + expect { client.get('/https://other.example/collect') }.to raise_error(ArgumentError, /absolute URL/) + end + + it 'refuses a path that opens with a scheme and no host' do + expect { client.get('http:/collect') }.to raise_error(ArgumentError, /absolute URL/) + end + + it 'takes a colon after the first segment, which leaves the path relative' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tags:x").to_return(json_response({})) + client.get('api/v1/tags:x') + expect(stub).to have_been_requested + end + + it 'sends a query string written into the path' do + stub = stub_request(:get, roles_url).with(query: { 'name' => 'prüfung', 'page' => '2' }).to_return(json_response([])) + + client.get('api/v1/roles?name=pr%C3%BCfung&page=2') + expect(stub).to have_been_requested + end + + it 'keeps a protocol-relative path on the instance' do + stub = stub_request(:get, 'http://zammad.test/other.example/collect').to_return(json_response([])) + + client.get('//other.example/collect') + expect(stub).to have_been_requested + end + + it 'passes query parameters' do + stub = stub_request(:get, roles_url).with(query: { 'active' => 'true' }).to_return(json_response([])) + + client.get('api/v1/roles', query: { active: true }) + expect(stub).to have_been_requested + end + + it 'carries an on_behalf_of scope' do + stub = stub_request(:get, roles_url) + .with(headers: { 'From' => 'agent@example.com' }) + .to_return(json_response([])) + + client.on_behalf_of('agent@example.com').get('api/v1/roles') + expect(stub).to have_been_requested + end + + it 'sends the headers it was given' do + stub = stub_request(:get, roles_url) + .with(headers: { 'Accept-Language' => 'de-de' }) + .to_return(json_response([])) + + client.get('api/v1/roles', headers: { 'Accept-Language' => 'de-de' }) + expect(stub).to have_been_requested + end + + it 'raises the mapped error class' do + stub_request(:get, roles_url).to_return(json_response({ error: 'nope' }, status: 403)) + + expect { client.get('api/v1/roles') }.to raise_error(ZammadAPI::AuthorizationError, /nope/) + end + + it 'names the request in the error message' do + stub_request(:get, roles_url).to_return(json_response({}, status: 500)) + + expect { client.get('api/v1/roles') } + .to raise_error(ZammadAPI::ServerError, 'GET api/v1/roles failed: HTTP 500') + end + + it 'leaves a query string written into the path out of the error message' do + stub_request(:get, roles_url).with(query: hash_including({})).to_return(json_response({}, status: 500)) + + expect { client.get('api/v1/roles?token=path-s3cret&page=2') } + .to raise_error(ZammadAPI::ServerError, 'GET api/v1/roles failed: HTTP 500') + end + end + + describe '#post' do + it 'sends a JSON body' do + stub = stub_request(:post, roles_url) + .with(body: JSON.generate({ name: 'Agent' }), headers: { 'Content-Type' => 'application/json' }) + .to_return(json_response({ id: 2 })) + + expect(client.post('api/v1/roles', body: { name: 'Agent' }).body).to eq({ id: 2 }) + expect(stub).to have_been_requested + end + + it 'sends the headers it was given' do + stub = stub_request(:post, roles_url).with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) + + client.post('api/v1/roles', body: {}, headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + end + + describe '#put' do + it 'sends a JSON body' do + stub = stub_request(:put, "#{roles_url}/1").with(body: JSON.generate({ name: 'Agent' })).to_return(json_response({ id: 1 })) + + client.put('api/v1/roles/1', body: { name: 'Agent' }) + expect(stub).to have_been_requested + end + + it 'sends the headers it was given' do + stub = stub_request(:put, "#{roles_url}/1").with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) + + client.put('api/v1/roles/1', body: {}, headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + end + + describe '#delete' do + it 'passes query parameters, which is how Zammad takes tag removals' do + stub = stub_request(:delete, "#{ClientHelper::BASE_URL}api/v1/tags/remove") + .with(query: { 'object' => 'Ticket', 'o_id' => '1', 'item' => 'urgent' }) + .to_return(json_response({ success: true })) + + client.delete('api/v1/tags/remove', query: { object: 'Ticket', o_id: 1, item: 'urgent' }) + expect(stub).to have_been_requested + end + + it 'sends the headers it was given' do + stub = stub_request(:delete, roles_url).with(headers: { 'X-Trace' => 'abc' }).to_return(json_response({})) + + client.delete('api/v1/roles', headers: { 'X-Trace' => 'abc' }) + expect(stub).to have_been_requested + end + end + end + + describe '#on_behalf_of' do + before do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + end + + it 'sends the From header' do + stub = stub_request(:get, url) + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 1 })) + + unit_client.on_behalf_of('agent@example.com').users.find(1) + expect(stub).to have_been_requested + end + + it 'leaves the original client unscoped' do + client = unit_client + client.on_behalf_of('someone') + client.users.find(1) + + expect(a_request(:get, url).with { |request| request.headers.key?('From') }).not_to have_been_made + end + + describe 'an identifier that names nobody' do + [nil, '', ' '].each do |blank| + it "refuses #{blank.inspect}" do + expect { unit_client.on_behalf_of(blank) }.to raise_error(ArgumentError, /on_behalf_of needs the login/) + end + end + end + + describe 'block form' do + it 'yields a scoped client' do + unit_client.on_behalf_of('agent@example.com') { |scoped| scoped.users.find(1) } + + expect(a_request(:get, url).with(query: hash_including({}), headers: { 'From' => 'agent@example.com' })) + .to have_been_made + end + + it 'returns the block value' do + expect(unit_client.on_behalf_of('agent@example.com') { :done }).to eq(:done) + end + end + end + + describe '#with' do + it 'applies the changed option' do + expect(unit_client.with(timeout: 5).config.timeout).to eq(5) + end + + it 'leaves the original client untouched' do + client = unit_client + client.with(timeout: 5) + expect(client.config.timeout).to eq(ZammadAPI::Config::DEFAULT_TIMEOUT) + end + + context 'when it names another way to authenticate' do + it 'sends the new credential' do + stub = stub_request(:get, url) + .with(query: hash_including({}), headers: { 'Authorization' => 'Bearer x' }) + .to_return(json_response({ id: 1 })) + + unit_client.with(oauth2_token: 'x').users.find(1) + expect(stub).to have_been_requested + end + end + + it 'carries an on_behalf_of scope over to the derived client' do + stub = stub_request(:get, url) + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' }) + .to_return(json_response({ id: 1 })) + + unit_client.on_behalf_of('agent@example.com').with(timeout: 5).users.find(1) + expect(stub).to have_been_requested + end + end + + describe '#inspect' do + it 'shows the url and auth scheme' do + expect(unit_client.inspect) + .to eq('#') + end + + it 'shows the user a scoped client acts for' do + expect(unit_client.on_behalf_of('agent@example.com').inspect) + .to eq('#') + end + end + + describe 'resource proxies' do + subject(:client) { unit_client } + + it 'hands out the same proxy for the same resource' do + first = client.tickets + + expect(client.tickets).to be(first) + end + + it 'refuses to be written to after it is built' do + expect(client.instance_variable_get(:@resources)).to be_frozen + end + + it 'gives a derived client a proxy that carries its own scope' do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1") + .with(query: hash_including({})).to_return(json_response({ id: 1 })) + + client.tickets + client.on_behalf_of('agent@example.com').tickets.find(1) + + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/1") + .with(query: hash_including({}), headers: { 'From' => 'agent@example.com' })).to have_been_made + end + end +end diff --git a/spec/unit/zammad_api/collection_spec.rb b/spec/unit/zammad_api/collection_spec.rb new file mode 100644 index 00000000..c5d1fdf1 --- /dev/null +++ b/spec/unit/zammad_api/collection_spec.rb @@ -0,0 +1,470 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Collection do + subject(:collection) { client.groups.all } + + let(:client) { unit_client } + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + # What a collection over this endpoint fetches per request when nothing asks + # for another size: as many as the endpoint serves. + def default_per_page = ZammadAPI::Resources::Group.page_limit + + def stub_page(page, records, per_page: default_per_page) + stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => page.to_s, 'per_page' => per_page.to_s }) + .to_return(json_response(records)) + end + + # The walk asks for another page only after a full one. + def full_page(first_id = 1) + Array.new(default_per_page) { { id: first_id + it } } + end + + describe '#each' do + it 'walks every page until the server runs out of records' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.map(&:id)).to eq((1..(default_per_page + 1)).to_a) + end + + it 'stops on a short first page without asking for the next' do + stub_page(1, [{ id: 1 }]) + + expect(collection.map(&:id)).to eq([1]) + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made + end + + it 'stops on an empty page' do + stub_page(1, full_page) + stub_page(2, []) + + expect(collection.map(&:id)).to eq((1..default_per_page).to_a) + end + + it 'yields persisted records' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(collection.first).to be_persisted + end + + it 'returns an Enumerator without a block' do + expect(collection.each).to be_a(Enumerator) + end + + it 'does not make a request until it is iterated' do + collection + expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made + end + + it 'works with lazy enumeration' do + stub_page(1, [{ id: 1 }, { id: 2 }]) + + expect(collection.lazy.map(&:id).first(2)).to eq([1, 2]) + end + + it 'raises ParseError when the endpoint does not return a list' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect { collection.to_a } + .to raise_error(ZammadAPI::ParseError, /expected a JSON array, got Hash/) + end + + it 'raises PaginationError when the endpoint ignores the page parameter' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response(full_page)) + + expect { collection.to_a } + .to raise_error(ZammadAPI::PaginationError, %r{\Aapi/v1/groups: page 2 repeated page 1, so the endpoint is ignoring the page parameter}) + end + + it 'does not hand the repeated page to the block before raising' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response(full_page)) + + batches = [] + + expect { collection.in_batches { batches << it } }.to raise_error(ZammadAPI::PaginationError) + expect(batches.size).to eq(1) + end + + # Pages are compared by the ids they hold, not by their payload. + it 'raises PaginationError when a repeated page comes back with its records changed' do + round = 0 + stub_request(:get, url).with(query: hash_including({})).to_return do + round += 1 + json_response(Array.new(default_per_page) { { id: it + 1, updated_at: "2026-11-18T10:00:#{format('%02d', round)}Z" } }) + end + + batches = 0 + + expect { Timeout.timeout(5) { collection.in_batches { batches += 1 } } } + .to raise_error(ZammadAPI::PaginationError, /ignoring the page parameter/) + expect(batches).to eq(1) + end + end + + describe '#find_each' do + it 'yields every record' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }], per_page: 2) + + ids = [] + collection.find_each(batch_size: 2) { ids << it.id } + expect(ids).to eq([1, 2, 3]) + end + + it 'walks at the default page size without one' do + stub_page(1, [{ id: 1 }]) + + ids = [] + collection.find_each { ids << it.id } + expect(ids).to eq([1]) + end + + it 'takes the page size inline' do + stub_page(1, [{ id: 1 }], per_page: 50) + + expect(collection.find_each(batch_size: 50).map(&:id)).to eq([1]) + end + + it 'returns an Enumerator without a block' do + expect(collection.find_each).to be_a(Enumerator) + end + end + + describe '#in_batches' do + it 'yields one array per page' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }], per_page: 2) + + batches = [] + collection.in_batches(of: 2) { batches << it.map(&:id) } + expect(batches).to eq([[1, 2], [3]]) + end + + it 'yields a whole page at the default size without one' do + stub_page(1, [{ id: 1 }, { id: 2 }]) + + batches = [] + collection.in_batches { batches << it.map(&:id) } + expect(batches).to eq([[1, 2]]) + end + + # The batch is the block's own Array, and working it off with `shift` is + # an ordinary way to consume one. + it 'keeps walking when the block empties the batch it was handed' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + stub_page(2, [{ id: 3 }], per_page: 2) + + ids = [] + collection.in_batches(of: 2) { |batch| ids << batch.shift.id until batch.empty? } + expect(ids).to eq([1, 2, 3]) + end + + it 'returns an Enumerator without a block' do + expect(collection.in_batches).to be_a(Enumerator) + end + + it 'pulls one page per Enumerator#next' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(collection.in_batches(of: 2).next.map(&:id)).to eq([1, 2]) + expect(a_request(:get, url).with(query: hash_including('page' => '2'))).not_to have_been_made + end + end + + describe '#page' do + it 'fetches only the requested page' do + stub_page(2, [{ id: 3 }, { id: 4 }]) + + expect(collection.page(2).map(&:id)).to eq([3, 4]) + expect(a_request(:get, url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + + it 'sizes the page, and so decides which records it holds' do + stub_page(2, [{ id: 3 }], per_page: 3) + + expect(collection.page(2, per_page: 3).map(&:id)).to eq([3]) + end + + it 'keeps the size when the page moves' do + stub_page(3, [{ id: 5 }], per_page: 3) + + expect(collection.page(2, per_page: 3).page(3).map(&:id)).to eq([5]) + end + + it 'returns a new collection and leaves the original unpaged' do + stub_page(1, [{ id: 1 }]) + + expect(collection.page(2)).not_to be(collection) + expect(collection.map(&:id)).to eq([1]) + end + end + + describe 'page size caps' do + it 'clamps a walk to what a generic index endpoint serves' do + stub_page(1, [], per_page: 1000) + + client.groups.all.find_each(batch_size: 5000).to_a + expect(a_request(:get, url).with(query: hash_including('per_page' => '1000'))).to have_been_made + end + + it 'clamps an explicit page to what the ticket index endpoint serves' do + expect(client.tickets.all.page(3, per_page: 500).inspect).to include('page=3').and include('per_page=100') + end + + it 'clamps an explicit page to what a search endpoint serves' do + expect(client.users.search('smith').page(1, per_page: 5000).inspect).to include('per_page=200') + end + end + + describe '#order' do + def sorted_request(sort_by, order_by) + a_request(:get, url).with(query: hash_including('sort_by' => sort_by, 'order_by' => order_by)) + end + + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } + + it 'sorts ascending by an attribute named on its own' do + collection.order(:name).to_a + expect(sorted_request('name', 'asc')).to have_been_made + end + + it 'sorts the way a keyword says' do + collection.order(name: :desc).to_a + expect(sorted_request('name', 'desc')).to have_been_made + end + + # Zammad pairs the two lists by position and skips an attribute that has + # no direction, so each attribute is sent with one. + it 'sorts by several attributes, each with a direction' do + collection.order(:active, name: :desc).to_a + expect(sorted_request('active,name', 'asc,desc')).to have_been_made + end + + it 'sorts within an earlier order when chained' do + collection.order(:active).order(name: :desc).to_a + expect(sorted_request('active,name', 'asc,desc')).to have_been_made + end + + it 'turns an attribute an earlier order named the way the later one says' do + collection.order(:name).order(name: :desc).to_a + expect(sorted_request('name', 'desc')).to have_been_made + end + + it 'leaves the collection it was called on unsorted' do + collection.order(:name) + collection.to_a + + expect(a_request(:get, url).with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s })) + .to have_been_made + end + + # TicketsController#index and UsersController#index hardcode the order and + # drop sort_by with everything else they do not read. + context 'with an index endpoint that is always served in id order' do + it 'refuses, rather than handing back records it would be calling sorted' do + expect { client.tickets.all.order(:title) } + .to raise_error(ArgumentError, %r{api/v1/tickets is always served in the same order and ignores sort_by}) + end + end + + context 'with a search' do + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/tickets/search" } + + before { stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) } + + it 'sorts, though the index of the same resource does not' do + client.tickets.search('printer').order(created_at: :desc).to_a + + expect(a_request(:get, search_url).with(query: hash_including('query' => 'printer', 'sort_by' => 'created_at', 'order_by' => 'desc'))) + .to have_been_made + end + end + end + + describe '#pluck' do + it 'returns one value per record for a single attribute' do + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(collection.pluck(:name)).to eq(%w[Users Support]) + end + + it 'returns one array per record for several attributes' do + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(collection.pluck(:id, :name)).to eq([[1, 'Users'], [2, 'Support']]) + end + end + + describe '#count' do + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + + it 'asks a search endpoint for the total in one request' do + stub_request(:get, search_url) + .with(query: { 'expand' => 'true', 'query' => 'smith', 'only_total_count' => 'true' }) + .to_return(json_response({ total_count: 4711 })) + + expect(client.users.search('smith').count).to eq(4711) + end + + # An index drops only_total_count with every other parameter it does not + # read, so there is no total to ask it for. + it 'walks an index endpoint rather than asking it for a total' do + stub_page(1, full_page) + stub_page(2, [{ id: default_per_page + 1 }]) + + expect(collection.count).to eq(default_per_page + 1) + expect(a_request(:get, url).with(query: hash_including('only_total_count' => 'true'))).not_to have_been_made + end + + it 'walks the pages when the total it answers with is not a count' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')) + .to_return(json_response([])) + stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) + .to_return(json_response({ total_count: 'lots' })) + + expect(client.users.search('smith').count).to eq(1) + end + + it 'walks the pages when something answers with records instead of a total' do + stub_request(:get, search_url).with(query: hash_including('page' => '1')) + .to_return(json_response([{ id: 1 }, { id: 2 }])) + stub_request(:get, search_url).with(query: hash_including('page' => '2')) + .to_return(json_response([])) + stub_request(:get, search_url).with(query: hash_including('only_total_count' => 'true')) + .to_return(json_response([{ id: 1 }, { id: 2 }])) + + expect(client.users.search('smith').count).to eq(2) + end + + it 'counts one page only when limited to a page' do + stub_page(3, [{ id: 5 }, { id: 6 }]) + + expect(collection.page(3).count).to eq(2) + end + + it 'counts matches when given a block' do + stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(collection.count { it.id > 1 }).to eq(2) + end + end + + describe '#empty?' do + it 'is false when the endpoint has a record' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect(collection).not_to be_empty + end + + it 'is true when the endpoint has none' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect(collection).to be_empty + end + + it 'asks for a single record rather than a whole page' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + collection.empty? + expect(a_request(:get, url).with(query: hash_including('per_page' => '1'))).to have_been_made + end + end + + # `find` on the proxy is the lookup by id, so the collection refuses an id + # rather than reading it as Enumerable#find's ifnone callable. + describe '#find' do + it 'is Enumerable#find with a block' do + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(collection.find { it.name == 'Support' }.id).to eq(2) + end + + it 'refuses an id where a block belongs, and names the lookup that takes one' do + expect { collection.find(1) } + .to raise_error(ArgumentError, 'find on a collection takes a block; look a record up by id with client..find(1)') + end + + it 'still returns an Enumerator without a block or an argument' do + expect(collection.find).to be_a(Enumerator) + end + end + + describe '#first' do + it 'reads a page of one for a single record' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(collection.first.id).to eq(1) + end + + it 'is nil when the endpoint has nothing' do + stub_page(1, [], per_page: 1) + + expect(collection.first).to be_nil + end + + it 'sizes the page to the number of records asked for' do + stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(collection.first(2).map(&:id)).to eq([1, 2]) + end + + # The page size of a collection limited to one says which records it + # holds, so re-sizing it would move them. + it 'leaves a collection already limited to a page at its own size' do + stub_page(3, [{ id: 5 }, { id: 6 }], per_page: 2) + + expect(collection.page(3, per_page: 2).first.id).to eq(5) + end + end + + describe '#inspect' do + it 'describes the collection without fetching it' do + expect(collection.inspect) + .to eq("#") + end + + it 'mentions the page when limited to one' do + expect(collection.page(4).inspect).to include('page=4') + end + end + + # A search names the ids for a page and then loads the records by id, so an + # id whose record is gone by then leaves the page one short, on any page. + # A search is therefore walked on to an empty page. + describe 'a search, which can serve a page short before the last one' do + subject(:search) { client.users.search('smith') } + + let(:search_url) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + let(:page_size) { ZammadAPI::Collection::SEARCH_MAX_PER_PAGE } + + def stub_search_page(page, records) + stub_request(:get, search_url) + .with(query: hash_including('page' => page.to_s)) + .to_return(json_response(records)) + end + + def hits(range) = range.map { { id: it } } + + it 'walks on past a page that came back short' do + stub_search_page(1, hits(1..page_size)) + stub_search_page(2, hits((page_size + 1)...(page_size * 2))) + stub_search_page(3, hits([900, 901])) + stub_search_page(4, []) + + expect(search.map(&:id)).to eq([*1...(page_size * 2), 900, 901]) + end + + it 'still reads only the one page a search was limited to' do + stub_search_page(2, hits(1..3)) + + expect(search.page(2).map(&:id)).to eq([1, 2, 3]) + expect(a_request(:get, search_url).with(query: hash_including('page' => '3'))).not_to have_been_made + end + end +end diff --git a/spec/unit/zammad_api/config_spec.rb b/spec/unit/zammad_api/config_spec.rb new file mode 100644 index 00000000..f7e9bb06 --- /dev/null +++ b/spec/unit/zammad_api/config_spec.rb @@ -0,0 +1,280 @@ +# frozen_string_literal: true + +require 'pp' + +RSpec.describe ZammadAPI::Config do + def build(url: 'https://zammad.example.com', http_token: 'token', **overrides) + described_class.new(url: url, http_token: http_token, **overrides) + end + + describe 'url handling' do + it 'appends a trailing slash so sub-path installations keep working' do + expect(build(url: 'https://example.com/zammad').url).to eq('https://example.com/zammad/') + end + + it 'leaves an existing trailing slash alone' do + expect(build(url: 'https://example.com/').url).to eq('https://example.com/') + end + + it 'rejects a missing url' do + expect { build(url: nil) } + .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') + end + + it 'rejects a non-http scheme' do + expect { build(url: 'ftp://example.com') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https:// and name a host') + end + + it 'rejects a url without a host' do + expect { build(url: 'https://') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https:// and name a host') + end + + it 'rejects a url that does not parse' do + expect { build(url: 'https://zammad example.com') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url is not a valid URL') + end + + it 'refuses credentials in the url, without quoting them' do + expect { build(url: 'https://admin:url-s3cret@zammad.example.com/') } + .to raise_error(ZammadAPI::ConfigurationError, 'config url carries credentials: pass user: and password:, or a token, instead') + end + end + + describe 'credentials' do + it 'accepts an access token' do + expect(build(http_token: 'token').authentication_scheme).to eq(:http_token) + end + + it 'accepts an OAuth2 token' do + expect(build(http_token: nil, oauth2_token: 'token').authentication_scheme).to eq(:oauth2_token) + end + + it 'accepts user and password' do + expect(build(http_token: nil, user: 'u', password: 'p').authentication_scheme).to eq(:basic) + end + + context 'with more than one way to authenticate' do + it 'refuses a token beside a user and password' do + expect { build(http_token: 'token', user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /config names more than one way to authenticate \(http_token, user and password\)/) + end + + it 'refuses all three, naming each' do + expect { build(http_token: 'token', oauth2_token: 'other', user: 'u', password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, /\(http_token, oauth2_token, user and password\)/) + end + + it 'refuses a token beside a user that has no password' do + expect { build(http_token: 'token', user: 'u') } + .to raise_error(ZammadAPI::ConfigurationError, /more than one way to authenticate/) + end + + it 'does not count a blank credential as one' do + expect(build(http_token: 'token', oauth2_token: '', user: nil, password: '').authentication_scheme).to eq(:http_token) + end + end + + it 'rejects a missing user' do + expect { build(http_token: nil, password: 'p') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + + it 'rejects a missing password' do + expect { build(http_token: nil, user: 'u') } + .to raise_error(ZammadAPI::ConfigurationError, 'missing password in config') + end + + it 'strips whitespace around a token' do + expect(build(http_token: " secret\n").http_token).to eq('secret') + end + + context 'with a token of only whitespace' do + it 'treats it as absent, for either token' do + expect { build(http_token: " \n") }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + expect { build(http_token: nil, oauth2_token: " \n") }.to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') + end + + it 'leaves the scheme it would have replaced in an override alone' do + expect(build(http_token: nil, user: 'u', password: 'p').with(http_token: " \n")).to have_attributes(http_token: nil, user: 'u', password: 'p') + end + end + + it 'keeps a password of spaces, which basic authentication carries as it is' do + expect(build(http_token: nil, user: 'u', password: ' ').password).to eq(' ') + end + end + + describe 'defaults' do + it 'sets a request timeout' do + expect(build.timeout).to eq(described_class::DEFAULT_TIMEOUT) + end + + it 'sets a connection timeout' do + expect(build.open_timeout).to eq(described_class::DEFAULT_OPEN_TIMEOUT) + end + + it 'retries transient failures' do + expect(build.retries).to eq(described_class::DEFAULT_RETRIES) + end + + it 'identifies itself with the gem version' do + expect(build.user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'verifies TLS certificates' do + expect(build.ssl_verify).to be(true) + end + + it 'discards log output when no logger is supplied' do + expect(build.logger).to be_a(Logger) + end + end + + describe 'the user agent' do + it 'falls back to the default when it is nil' do + expect(build(user_agent: nil).user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'falls back to the default when it is only whitespace' do + expect(build(user_agent: " \t\n").user_agent).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'strips whitespace around it' do + expect(build(user_agent: ' my-app/1.0 ').user_agent).to eq('my-app/1.0') + end + end + + describe 'the Faraday seam' do + it 'symbolizes an adapter given as a string' do + expect(build(adapter: 'test').adapter).to eq(:test) + end + + it 'keeps the middleware callable' do + hook = ->(builder) { builder } + expect(build(middleware: hook).middleware).to be(hook) + end + end + + describe 'the logger' do + it 'keeps the logger it is given' do + logger = Logger.new(IO::NULL) + expect(build(logger: logger).logger).to be(logger) + end + end + + describe '#inspect' do + subject(:rendered) { build(http_token: nil, user: 'u', password: 'pw-s3cret').inspect } + + it 'redacts the password' do + expect(rendered).not_to include('pw-s3cret') + end + + it 'redacts the access token' do + expect(build(http_token: 'tok-s3cret').inspect).not_to include('tok-s3cret') + end + + it 'redacts the OAuth2 token' do + expect(build(http_token: nil, oauth2_token: 'oauth-s3cret').inspect).not_to include('oauth-s3cret') + end + + it 'marks redacted values' do + expect(rendered).to include('password=[REDACTED]') + end + + it 'keeps non-sensitive values readable' do + expect(rendered).to include('url="https://zammad.example.com/"') + end + + it 'does not dump the logger internals' do + expect(rendered).to include('logger=#') + end + + it 'does not dump the middleware internals' do + expect(build(middleware: ->(builder) { builder }).inspect).to include('middleware=#') + end + + it 'still shows that no middleware is configured' do + expect(rendered).to include('middleware=nil') + end + + it 'is used for to_s as well' do + config = build(http_token: nil, user: 'u', password: 'hunter2') + expect(config.to_s).to eq(config.inspect) + end + + context 'with an authenticated proxy' do + subject(:rendered) { build(proxy: 'http://puser:pproxy-s3cret@proxy.test:8080').inspect } + + it 'marks the redacted userinfo' do + expect(rendered).to include('proxy="http://[REDACTED]@proxy.test:8080"') + end + end + + it 'leaves a proxy without credentials alone' do + expect(build(proxy: 'http://proxy.test:8080').inspect).to include('proxy="http://proxy.test:8080"') + end + end + + describe 'pretty printing' do + it 'prints what inspect prints' do + config = build(http_token: nil, user: 'u', password: 'hunter2') + expect(config.pretty_inspect).to eq("#{config.inspect}\n") + end + end + + describe '#with' do + it 'changes an option' do + expect(build.with(timeout: 5).timeout).to eq(5) + end + + it 'keeps the rest' do + expect(build(proxy: 'http://proxy.test:8080').with(timeout: 5).proxy).to eq('http://proxy.test:8080') + end + + it 're-validates' do + expect { build.with(url: 'zammad.example.com') }.to raise_error(ZammadAPI::ConfigurationError, /needs to start with http/) + end + + it 'replaces the authentication scheme rather than adding a second one' do + derived = build.with(user: 'u', password: 'p') + expect(derived.to_h.slice(:http_token, :user, :password)).to eq({ http_token: nil, user: 'u', password: 'p' }) + end + + it 'does not read an explicit nil as naming a scheme' do + expect(build.with(oauth2_token: nil).authentication_scheme).to eq(:http_token) + end + + it 'can switch to any scheme from any other without naming two at once' do + switched = build.with(oauth2_token: 'o').with(user: 'u', password: 'p').with(http_token: 't') + expect(switched.to_h.slice(:http_token, :oauth2_token, :user, :password)) + .to eq({ http_token: 't', oauth2_token: nil, user: nil, password: nil }) + end + end + + describe '.merge_options' do + it 'lays the overrides over the options' do + expect(described_class.merge_options({ url: 'a', timeout: 1 }, { timeout: 2 })).to eq({ url: 'a', timeout: 2 }) + end + + it 'drops the credentials an override replaces' do + expect(described_class.merge_options({ http_token: 't' }, { oauth2_token: 'o' })).to eq({ oauth2_token: 'o' }) + end + + it 'keeps the other half of a scheme the override names' do + expect(described_class.merge_options({ user: 'u', password: 'old' }, { password: 'new' })) + .to eq({ user: 'u', password: 'new' }) + end + + it 'leaves the credentials alone when the overrides name none' do + expect(described_class.merge_options({ http_token: 't' }, { timeout: 2 })).to eq({ http_token: 't', timeout: 2 }) + end + end + + describe 'other options' do + it 'reads an empty proxy as none' do + expect(build(proxy: '').proxy).to be_nil + end + end +end diff --git a/spec/unit/zammad_api/resource_proxy_spec.rb b/spec/unit/zammad_api/resource_proxy_spec.rb new file mode 100644 index 00000000..74771c31 --- /dev/null +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -0,0 +1,458 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::ResourceProxy do + subject(:proxy) { client.groups } + + let(:client) { unit_client } + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + it 'exposes the resource class' do + expect(proxy.resource_class).to eq(ZammadAPI::Resources::Group) + end + + describe '#new' do + it 'builds an unsaved record' do + expect(proxy.new(name: 'Support')).to be_new_record + end + + it 'accepts no attributes at all' do + expect(proxy.new.attributes).to eq({}) + end + end + + describe '#find' do + it 'requests the record with expanded attributes' do + stub = stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }).to_return(json_response({ id: 1, name: 'Users' })) + + proxy.find(1) + expect(stub).to have_been_requested + end + + it 'returns a persisted record' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + expect(proxy.find(1)).to be_persisted + end + + it 'raises NotFoundError for an unknown id' do + stub_request(:get, "#{url}/404").with(query: hash_including({})).to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.find(404) }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'raises ParseError when the response is not an object' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect { proxy.find(1) }.to raise_error(ZammadAPI::ParseError, /expected a JSON object, got Array/) + end + end + + describe 'ids in the request path' do + it 'escapes a traversal instead of reaching another endpoint' do + stub = stub_request(:get, "#{url}/1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1") + .with(query: { 'expand' => 'true' }) + .to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.find('1/../../api/v1/users/1') }.to raise_error(ZammadAPI::NotFoundError) + expect(stub).to have_been_requested + expect(a_request(:get, %r{/api/v1/users/1\z})).not_to have_been_made + end + + it 'rejects an empty id rather than requesting the index' do + expect { proxy.find('') }.to raise_error(ArgumentError, /record id is required/) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + + describe '#create' do + it 'posts the attributes' do + stub = stub_request(:post, url) + .with(query: { 'expand' => 'true' }, body: '{"name":"Support"}') + .to_return(json_response({ id: 5, name: 'Support' }, status: 201)) + + proxy.create(name: 'Support') + expect(stub).to have_been_requested + end + + it 'returns the persisted record' do + stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 5, name: 'Support' }, status: 201)) + + expect(proxy.create(name: 'Support')).to be_persisted + end + + it 'raises ValidationError when Zammad rejects the attributes' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + + expect { proxy.create({}) }.to raise_error(ZammadAPI::ValidationError, /Name is required/) + end + end + + describe '#find_by' do + let(:search_url) { "#{url}/search" } + + context 'with an id' do + it 'reads the record by its id, given as text' do + stub_request(:get, "#{url}/5").with(query: { expand: 'true' }).to_return(json_response({ id: 5, name: 'Users' })) + + expect(proxy.find_by(id: '5').id).to eq(5) + expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made + end + + it 'checks the other values against it' do + stub_request(:get, "#{url}/5").with(query: { expand: 'true' }).to_return(json_response({ id: 5, name: 'Users' })) + + expect(proxy.find_by(id: 5, name: 'Other')).to be_nil + end + + it 'answers nil for an id that names no record' do + stub_request(:get, "#{url}/9").with(query: { expand: 'true' }).to_return(json_response({ error: 'not found' }, status: 404)) + + expect(proxy.find_by(id: 9)).to be_nil + end + end + + it 'searches instead of filtering an index that cannot filter' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'Users')) + .to_return(json_response([{ id: 1, name: 'Users' }])) + + proxy.find_by(name: 'Users') + + expect(stub).to have_been_requested + expect(a_request(:get, url).with(query: hash_including({}))).not_to have_been_made + end + + it 'returns the matching record' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) + + expect(proxy.find_by(name: 'Users').id).to eq(1) + end + + # Zammad's search sorts by updated_at, newest first, not by relevance, so + # the exact match can sit on any page of hits. + context 'when more records match the term than one page holds' do + let(:page_size) { ZammadAPI::Collection::SEARCH_MAX_PER_PAGE } + let(:others) { Array.new(page_size) { { id: it + 1, name: 'Users Archive' } } } + + def stub_page(number, records) + stub_request(:get, search_url) + .with(query: hash_including('page' => number.to_s)) + .to_return(json_response(records)) + end + + it 'finds a match on a later page' do + stub_page(1, others) + stub_page(2, [{ id: 999, name: 'Users' }]) + + expect(proxy.find_by(name: 'Users').id).to eq(999) + end + end + + it 'skips a hit the search returned that does not actually match' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users Archive' }, { id: 2, name: 'Users' }])) + + expect(proxy.find_by(name: 'Users').id).to eq(2) + end + + it 'returns nil when nothing matched' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect(proxy.find_by(name: 'Nope')).to be_nil + end + + it 'matches on every attribute given, not just one' do + stub_request(:get, search_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Users', active: true }])) + + expect(proxy.find_by(name: 'Users', active: true).id).to eq(2) + end + + it 'searches the longest value, as the most selective of them' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'a-very-specific-note')) + .to_return(json_response([])) + + proxy.find_by(name: 'Users', note: 'a-very-specific-note') + expect(stub).to have_been_requested + end + + it 'keeps a non-string value out of the search term, and still matches on it' do + stub = stub_request(:get, search_url) + .with(query: hash_including('query' => 'Users')) + .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Users', active: true }])) + + expect(proxy.find_by(name: 'Users', active: true).id).to eq(2) + expect(stub).to have_been_requested + end + + it 'rejects a lookup with no attribute at all' do + expect { proxy.find_by }.to raise_error(ArgumentError, /at least one attribute/) + end + + context 'with a resource Zammad routes no search endpoint for' do + let(:states_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_states" } + + before do + stub_request(:get, states_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'new', state_type_id: 1 }, { id: 2, name: 'open', state_type_id: 2 }])) + end + + it 'walks the records and answers with the one that matches' do + expect(client.ticket_states.find_by(name: 'open').id).to eq(2) + end + end + + # Zammad matches words, so a value that is not a string would go out as + # the word it prints as. + context 'with no string value to search on' do + before do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users', active: false }, { id: 2, name: 'Support', active: true }])) + end + + it 'walks the index and answers with the first record that matches' do + expect(proxy.find_by(active: true).id).to eq(2) + end + + it 'walks for a string value that is blank, which is nothing to search on either' do + expect(proxy.find_by(name: ' ', active: true)).to be_nil + expect(a_request(:get, search_url).with(query: hash_including({}))).not_to have_been_made + end + end + + it 'does not match nil against an attribute the record does not carry' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users' }])) + + expect(proxy.find_by(nmae: nil)).to be_nil + end + + it 'does match nil against an attribute the record carries as nil' do + stub_request(:get, url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, name: 'Users', note: nil }])) + + expect(proxy.find_by(note: nil).id).to eq(1) + end + end + + describe '#find_by!' do + let(:search_url) { "#{url}/search" } + + it 'returns the matching record' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([{ id: 1, name: 'Users' }])) + + expect(proxy.find_by!(name: 'Users').id).to eq(1) + end + + it 'raises NotFoundError when nothing matched' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect { proxy.find_by!(name: 'Nope') }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'names the resource and the attributes in the message' do + stub_request(:get, search_url).with(query: hash_including({})).to_return(json_response([])) + + expect { proxy.find_by!(name: 'Nope', active: true) } + .to raise_error('no ZammadAPI::Resources::Group matched name and active') + end + end + + describe '#exists?' do + it 'is true when the record is there' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect(proxy.exists?(1)).to be(true) + end + + it 'is false for a 404' do + stub_request(:get, "#{url}/404").with(query: hash_including({})) + .to_return(json_response({ error: 'not found' }, status: 404)) + + expect(proxy.exists?(404)).to be(false) + end + + it 'does not swallow an authorization failure' do + stub_request(:get, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'no' }, status: 403)) + + expect { proxy.exists?(1) }.to raise_error(ZammadAPI::AuthorizationError) + end + end + + describe '#destroy' do + it 'deletes the record without fetching it first' do + stub = stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + + expect(proxy.destroy(1)).to be(true) + expect(stub).to have_been_requested + expect(a_request(:get, "#{url}/1")).not_to have_been_made + end + + it 'raises NotFoundError for an unknown id' do + stub_request(:delete, "#{url}/404").to_return(json_response({ error: 'not found' }, status: 404)) + + expect { proxy.destroy(404) }.to raise_error(ZammadAPI::NotFoundError) + end + end + + # What a collection over this endpoint fetches per request when nothing asks + # for another size: as many as the endpoint serves. + def default_per_page = ZammadAPI::Resources::Group.page_limit + + describe '#all' do + it 'returns a collection' do + expect(proxy.all).to be_a(ZammadAPI::Collection) + end + + it 'defaults to the collection page size' do + stub = stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s }) + .to_return(json_response([])) + + proxy.all.to_a + expect(stub).to have_been_requested + end + end + + describe '#order' do + it 'returns a sorted collection of every record' do + stub = stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => default_per_page.to_s, 'sort_by' => 'name', 'order_by' => 'desc' }) + .to_return(json_response([])) + + proxy.order(name: :desc).to_a + expect(stub).to have_been_requested + end + end + + describe 'enumerating a proxy directly' do + def stub_page(page, records, per_page: default_per_page) + stub_request(:get, url) + .with(query: { 'expand' => 'true', 'page' => page.to_s, 'per_page' => per_page.to_s }) + .to_return(json_response(records)) + end + + it 'yields every record from #each' do + stub_page(1, [{ id: 1, name: 'Users' }, { id: 2, name: 'Support' }]) + + expect(proxy.map(&:name)).to eq(%w[Users Support]) + end + + # Forwarded to the collection rather than left to Enumerable#first, which + # would take one record off the front of a page sized for walking. + it 'reads one sized page for #first, without walking everything' do + stub_page(1, [{ id: 1 }], per_page: 1) + + expect(proxy.first.id).to eq(1) + expect(a_request(:get, url).with(query: hash_including({ 'page' => '2' }))).not_to have_been_made + end + + it 'reads one page of that size for #first with a count' do + stub = stub_page(1, [{ id: 1 }, { id: 2 }], per_page: 2) + + expect(proxy.first(2).map(&:id)).to eq([1, 2]) + expect(stub).to have_been_requested.once + end + + it 'counts every record' do + stub_page(1, [{ id: 1 }, { id: 2 }, { id: 3 }]) + + expect(proxy.count).to eq(3) + end + + it 'forwards #page to the collection' do + stub = stub_request(:get, url) + .with(query: hash_including({ 'page' => '3' })) + .to_return(json_response([])) + + proxy.page(3).to_a + expect(stub).to have_been_requested + end + + it 'forwards #find_each' do + stub_page(1, [{ id: 1 }], per_page: 5) + + ids = [] + proxy.find_each(batch_size: 5) { ids << it.id } + expect(ids).to eq([1]) + end + + it 'forwards #in_batches' do + stub_page(1, [{ id: 1 }], per_page: 5) + + sizes = [] + proxy.in_batches(of: 5) { sizes << it.size } + expect(sizes).to eq([1]) + end + + it 'forwards #pluck' do + stub_page(1, [{ id: 1, name: 'Users' }]) + + expect(proxy.pluck(:name)).to eq(['Users']) + end + + it 'forwards #empty?' do + stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) + + expect(proxy).to be_empty + end + end + + describe '#search' do + it 'refuses a resource Zammad routes no search endpoint for' do + expect { client.ticket_states.search('open') } + .to raise_error(ZammadAPI::Error, /routes no search endpoint for ZammadAPI::Resources::TicketState/) + end + + it 'requests the search endpoint' do + stub = stub_request(:get, "#{url}/search") + .with(query: { 'expand' => 'true', 'page' => '1', 'per_page' => ZammadAPI::Collection::SEARCH_MAX_PER_PAGE.to_s, 'query' => 'support' }) + .to_return(json_response([])) + + proxy.search('support').to_a + expect(stub).to have_been_requested + end + + # Keywords go to the search endpoint as they are, for what it narrows by + # besides the term. + context 'with keywords' do + let(:users_search) { "#{ClientHelper::BASE_URL}api/v1/users/search" } + + before { stub_request(:get, /search/).with(query: hash_including({})).to_return(json_response([])) } + + it 'sends ids' do + client.users.search('x', ids: [1, 2]).to_a + expect(a_request(:get, users_search).with(query: hash_including('query' => 'x', 'ids' => %w[1 2]))).to have_been_made + end + + it 'sends a condition the way Rails reads a nested parameter back' do + client.tickets.search('x', condition: { 'ticket.state_id' => { operator: 'is', value: [1] } }).to_a + + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/tickets/search") + .with(query: hash_including('condition' => { 'ticket.state_id' => { 'operator' => 'is', 'value' => ['1'] } }))) + .to have_been_made + end + end + + it 'rejects an empty term' do + expect { proxy.search(' ') }.to raise_error(ArgumentError, /non-empty query string/) + end + + it "says that '*' asks for every record" do + expect { proxy.search('') }.to raise_error(ArgumentError, /Search for '\*' to ask for every record/) + end + + it 'rejects a term that is not a string' do + expect { proxy.search(42) }.to raise_error(ArgumentError, /non-empty query string/) + end + end + + describe '#inspect' do + it 'names the resource' do + expect(proxy.inspect).to eq('#') + end + end +end diff --git a/spec/unit/zammad_api/resources/base_spec.rb b/spec/unit/zammad_api/resources/base_spec.rb new file mode 100644 index 00000000..336696c2 --- /dev/null +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -0,0 +1,558 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Resources::Base do + let(:client) { unit_client } + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + describe 'the path DSL' do + it 'exposes the declared path' do + expect(ZammadAPI::Resources::Group.resource_path).to eq('api/v1/groups') + end + + it 'raises for a resource that declares none' do + anonymous = Class.new(described_class) do + def self.name + 'Anonymous' + end + end + expect { anonymous.resource_path }.to raise_error(ZammadAPI::Error, /does not declare an API path/) + end + end + + describe 'attributes' do + subject(:group) { client.groups.new(name: 'Support', 'note' => 'from a string key') } + + it 'reads an attribute' do + expect(group.name).to eq('Support') + end + + it 'starts without changes' do + expect(group).not_to be_changed + end + + # What a Rails controller holds: not a Hash, but it converts to one. + context 'when given strong parameters, which convert to a Hash and are not one' do + subject(:user) { client.users.new(permitted) } + + let(:permitted) { StrongParameters.new(login: 'jane', password: 'hunter2', preferences: StrongParameters.new(locale: 'de')) } + + it 'holds them as attributes of its own' do + expect(user.attributes).to eq(login: 'jane', password: 'hunter2', preferences: { locale: 'de' }) + end + end + + it 'records a change as old and new value' do + group.name = 'Other' + expect(group.changes).to eq(name: %w[Support Other]) + end + + it 'reports being changed' do + group.name = 'Other' + expect(group).to be_changed + end + + it 'reflects the change when read back' do + group.name = 'Other' + expect(group.name).to eq('Other') + end + + it 'records a change for a previously unset attribute' do + group.active = true + expect(group.changes).to eq(active: [nil, true]) + end + + it 'keeps the original value when an attribute is written twice' do + group.name = 'First' + group.name = 'Second' + expect(group.changes).to eq(name: %w[Support Second]) + end + + it 'drops the change when the value returns to the original' do + group.name = 'Other' + group.name = 'Support' + expect(group.changes).to be_empty + end + + it 'drops the change when an attribute the record carries is set back to its nil original' do + carrying_nil = client.groups.new(name: 'Support', note: nil) + carrying_nil.note = 'Renamed' + carrying_nil.note = nil + expect(carrying_nil.changes).to be_empty + end + + # An attribute the record does not carry is not one whose value is nil. + it 'stages a write of an attribute the record does not carry' do + group.active = nil + expect(group.changes).to eq(active: [nil, nil]) + end + end + + describe 'attribute state a record hands out' do + subject(:group) { client.groups.new(name: 'Support', preferences: { 'note' => 'keep' }) } + + it 'cannot be written through #changes, which would decide what save sends' do + group.name = 'Renamed' + expect { group.changes[:name] = %w[a b] }.to raise_error(FrozenError) + end + + it 'keeps a value the caller mutates after assigning it' do + note = +'Mutable' + group.note = note + note << ' changed' + + expect(group.note).to eq('Mutable') + end + + it 'freezes attributes adopted from a response' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ id: 7, preferences: { note: 'from the server' } }, status: 201)) + + group.save! + expect { group.attributes[:preferences][:note] << '!' }.to raise_error(FrozenError) + end + end + + describe '#save' do + context 'with a new record' do + subject(:group) { client.groups.new(name: 'Support') } + + before do + stub_request(:post, url) + .with(query: { 'expand' => 'true' }, body: '{"name":"Support"}') + .to_return(json_response({ id: 7, name: 'Support', note: nil }, status: 201)) + end + + it 'returns true' do + expect(group.save).to be(true) + end + + it 'adopts the attributes from the response' do + group.save + expect(group.id).to eq(7) + end + + it 'is no longer a new record' do + group.save + expect(group).to be_persisted + end + + it 'clears the staged changes' do + group.name = 'Support' + group.save + expect(group.changes).to be_empty + end + end + + context 'with an existing record' do + subject(:group) { client.groups.find(1) } + + before do + stub_request(:get, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1, name: 'Users', note: 'old', active: true })) + end + + it 'sends only the changed attributes' do + stub = stub_request(:put, "#{url}/1") + .with(query: { 'expand' => 'true' }, body: '{"note":"new"}') + .to_return(json_response({ id: 1, name: 'Users', note: 'new', active: true })) + + group.note = 'new' + group.save + expect(stub).to have_been_requested + end + + it 'takes on what Zammad answered, and has nothing left to save' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1, name: 'Users', note: 'new', active: true, updated_at: '2026-01-01T00:00:00Z' })) + + group.note = 'new' + group.save + + expect(group.updated_at).to eq('2026-01-01T00:00:00Z') + expect(group.changes).to be_empty + end + + it 'sends nothing at all when nothing changed' do + stub = stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ id: 1 })) + + expect(group.save).to be(true) + expect(stub).not_to have_been_requested + end + end + + it 'raises ParseError when the response is not an object' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response([], status: 201)) + + expect { client.groups.new(name: 'x').save } + .to raise_error(ZammadAPI::ParseError, /expected a JSON object, got Array/) + end + + context 'when Zammad rejects the attributes' do + subject(:group) { client.groups.new } + + before do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + end + + it 'returns false instead of raising' do + expect(group.save).to be(false) + end + + it 'leaves the validation error in #error' do + group.save + expect(group.error).to be_a(ZammadAPI::ValidationError) + end + + it 'leaves the record unsaved' do + group.save + expect(group).to be_new_record + end + + it 'keeps the staged changes, so the attributes can be corrected and resent' do + group.name = 'Support' + group.save + expect(group.changes).to eq({ name: [nil, 'Support'] }) + end + end + + context 'when the failure is not a validation error' do + it 'still raises for a 403' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'no' }, status: 403)) + + expect { client.groups.new(name: 'x').save }.to raise_error(ZammadAPI::AuthorizationError) + end + end + + it 'clears a previous error once the record saves' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422), json_response({ id: 7, name: 'Support' })) + + group = client.groups.new + group.save + group.name = 'Support' + + expect(group.save).to be(true) + expect(group.error).to be_nil + end + end + + describe '#save!' do + subject(:group) { client.groups.new(name: 'Support') } + + it 'returns true' do + stub_request(:post, url).with(query: hash_including({})).to_return(json_response({ id: 7 }, status: 201)) + + expect(group.save!).to be(true) + end + + it 'raises ValidationError when Zammad rejects the record' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + + expect { group.save! }.to raise_error(ZammadAPI::ValidationError, /Name is required/) + end + + it 'does not record the error, because it was raised' do + stub_request(:post, url).with(query: hash_including({})) + .to_return(json_response({ error: 'Name is required' }, status: 422)) + + expect { group.save! }.to raise_error(ZammadAPI::ValidationError) + expect(group.error).to be_nil + end + end + + describe '#assign_attributes' do + subject(:group) { client.groups.new(name: 'Support') } + + it 'stages every attribute as a change' do + group.assign_attributes(name: 'Renamed', note: 'Why') + expect(group.changes).to eq(name: %w[Support Renamed], note: [nil, 'Why']) + end + + it 'accepts string keys' do + group.assign_attributes('name' => 'Renamed') + expect(group.name).to eq('Renamed') + end + + it 'returns the record, so it can be chained' do + expect(group.assign_attributes(name: 'Renamed')).to be(group) + end + + # `record.update(params.require(:group).permit(:name))` + context 'with strong parameters' do + it 'stages what they convert to' do + group.assign_attributes(StrongParameters.new(name: 'Renamed', note: 'Why')) + + expect(group.changes).to eq(name: %w[Support Renamed], note: [nil, 'Why']) + end + end + end + + describe '#update' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users', note: 'old') } + + it 'sends only the assigned attributes' do + stub = stub_request(:put, "#{url}/1") + .with(query: { 'expand' => 'true' }, body: '{"note":"new"}') + .to_return(json_response({ id: 1, name: 'Users', note: 'new' })) + + group.update(note: 'new') + expect(stub).to have_been_requested + end + + it 'returns false and records the error when Zammad rejects the attributes' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'Note is too long' }, status: 422)) + + expect(group.update(note: 'new')).to be(false) + expect(group.error.server_message).to eq('Note is too long') + end + end + + describe '#update!' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, note: 'old') } + + it 'returns true' do + stub_request(:put, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect(group.update!(note: 'new')).to be(true) + end + + it 'raises when Zammad rejects the attributes' do + stub_request(:put, "#{url}/1").with(query: hash_including({})) + .to_return(json_response({ error: 'Note is too long' }, status: 422)) + + expect { group.update!(note: 'new') }.to raise_error(ZammadAPI::ValidationError, /Note is too long/) + end + end + + describe '#reload' do + subject(:group) { ZammadAPI::Resources::Group.from_response(transport, id: 1, name: 'Users') } + + let(:transport) { unit_transport } + + before do + stub_request(:get, "#{url}/1").with(query: { 'expand' => 'true' }) + .to_return(json_response({ id: 1, name: 'Renamed' })) + end + + it 'refetches the attributes' do + expect(group.reload.name).to eq('Renamed') + end + + it 'discards unsaved changes' do + group.name = 'Local' + expect(group.reload.changes).to be_empty + end + + it 'returns itself' do + expect(group.reload).to be(group) + end + + it 'raises for a record that was never saved' do + expect { ZammadAPI::Resources::Group.new(transport).reload } + .to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to reload/) + end + end + + describe '.member_path' do + it 'builds the path of one record' do + expect(ZammadAPI::Resources::Group.member_path(1)).to eq('api/v1/groups/1') + end + + # ResourceProxy#find, #destroy and every instance method that reaches an + # endpoint go through here, so the escaping rule is applied once. + it 'escapes an id that would otherwise leave its segment' do + expect(ZammadAPI::Resources::Group.member_path('1/../users')).to eq('api/v1/groups/1%2F..%2Fusers') + end + end + + describe '#destroy' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1) } + + it 'deletes the record' do + stub = stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + expect(group.destroy).to be(true) + expect(stub).to have_been_requested + end + + it 'sends nothing for a record built with an id it was never saved with' do + stub = stub_request(:delete, "#{url}/99") + + expect { client.groups.new(id: 99, name: 'X').destroy } + .to raise_error(ZammadAPI::Error, /has not been saved, so there is nothing to destroy/) + expect(stub).not_to have_been_requested + end + + context 'when the record is gone' do + before do + stub_request(:delete, "#{url}/1").to_return(status: 200, body: '') + group.destroy + end + + it 'reports the record as destroyed' do + expect(group).to be_destroyed + end + + it 'no longer reports it as persisted' do + expect(group).not_to be_persisted + end + + it 'says so in inspect' do + expect(group.inspect).to include('destroyed=true') + end + end + end + + describe 'equality' do + it 'treats two separately fetched records as the same record' do + stub_request(:get, "#{url}/1").with(query: hash_including({})).to_return(json_response({ id: 1, name: 'Users' })) + + first_fetch = client.groups.find(1) + second_fetch = client.groups.find(1) + + expect(first_fetch).not_to equal(second_fetch) + expect(first_fetch).to eq(second_fetch) + end + end + + describe '#inspect' do + it 'shows the id, state and attributes' do + group = ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') + expect(group.inspect) + .to eq('#') + end + + # A record is printed by IRB, by pp, in an RSpec failure and in an + # exception report, and a user is given a password by staging one. + context 'with an attribute that names a credential' do + let(:user) { client.users.new(login: 'x', password: 'hunter2', preferences: { tokens: [{ access_token: 's3cret' }], locale: 'de' }) } + + it 'blanks a staged password' do + expect(user.inspect).to include('password: "[REDACTED]"').and include('login: "x"') + end + end + end + + describe '.from_response' do + it 'builds a persisted record' do + expect(ZammadAPI::Resources::Group.from_response(unit_transport, id: 1)).to be_persisted + end + end + + describe 'a resource subclassed by a caller' do + subject(:subclass) { Class.new(ZammadAPI::Resources::Ticket) { def self.name = 'MyTicket' } } + + it 'inherits the API path' do + expect(subclass.resource_path).to eq('api/v1/tickets') + end + + it 'lets a subclass declare a path of its own' do + own = Class.new(ZammadAPI::Resources::Ticket) { path 'api/v1/my_tickets' } + + expect(own.resource_path).to eq('api/v1/my_tickets') + end + end + + describe 'the endpoint declarations' do + it 'defaults to unsearchable, so an unrouted /search is refused at the call site' do + expect(Class.new(described_class).searchable?).to be(false) + end + + it 'defaults to the generic index page limit' do + expect(Class.new(described_class).page_limit).to eq(described_class::DEFAULT_MAX_PER_PAGE) + end + + it 'defaults to an index endpoint that sorts, as the generic ones do' do + expect(Class.new(described_class).sortable?).to be(true) + end + + it 'records a declared page limit' do + expect(Class.new(described_class) { max_per_page 25 }.page_limit).to eq(25) + end + + it 'records a declaration that the index endpoint does not sort' do + expect(Class.new(described_class) { sortable false }.sortable?).to be(false) + end + + it 'declares tickets and users unsortable, whose controllers hardcode the order' do + expect([ZammadAPI::Resources::Ticket, ZammadAPI::Resources::User].map(&:sortable?)).to eq([false, false]) + end + end + + describe '#[]=' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } + + it 'stages the attribute it names' do + group[:note] = 'x' + + expect(group.changes).to eq({ note: [nil, 'x'] }) + end + + it 'takes a string key the way the reader does' do + group['note'] = 'x' + + expect(group[:note]).to eq('x') + end + end + + describe 'writing the id' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, id: 1, name: 'Users') } + + it 'is refused' do + expect { group.id = 99 } + .to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Group#id cannot be changed: it is what addresses this record') + end + + it 'is taken by the constructor' do + expect(client.groups.new(id: 5).id).to eq(5) + end + end + + describe 'a record Zammad served without an id' do + subject(:group) { ZammadAPI::Resources::Group.from_response(unit_transport, name: 'Users') } + + it 'refuses a reload it cannot address' do + expect { group.reload }.to raise_error(ZammadAPI::Error, 'ZammadAPI::Resources::Group has no id, save it first') + end + end + + # Zammad answers a create and an update with a JSON object, so a 2xx with + # anything else is the page of something in front of it: a login page, a + # captive portal, the default page of a load balancer. + describe 'a save answered 2xx by something that is not Zammad' do + def login_page + { status: 200, body: 'Please sign in', headers: { 'Content-Type' => 'text/html' } } + end + + def swallow + yield + rescue ZammadAPI::ParseError + nil + end + + context 'when it was a create' do + subject(:group) { client.groups.new(name: 'Support') } + + before do + stub_request(:post, url).with(query: hash_including({})) + .to_return(login_page, json_response({ id: 7, name: 'Support' }, status: 201)) + end + + it 'still reports the parse failure' do + expect { group.save }.to raise_error(ZammadAPI::ParseError, /expected a JSON object, got String/) + end + + it 'leaves the record new' do + swallow { group.save } + + expect(group.new_record?).to be(true) + expect(group.persisted?).to be(false) + end + end + end +end diff --git a/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb new file mode 100644 index 00000000..f6c5343b --- /dev/null +++ b/spec/unit/zammad_api/resources/ticket_article_attachment_spec.rb @@ -0,0 +1,93 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Resources::TicketArticleAttachment do + let(:transport) { unit_transport } + let(:download_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_attachment/42/9/3" } + + describe 'built from an article' do + subject(:attachment) { article.attachments.first } + + let(:article) do + ZammadAPI::Resources::TicketArticle.from_response( + transport, + id: 9, + ticket_id: 42, + attachments: [{ id: 3, filename: 'note.txt', size: '12' }] + ) + end + + it 'carries the attachment id' do + expect(attachment.id).to eq(3) + end + + it 'carries the filename' do + expect(attachment.filename).to eq('note.txt') + end + + it 'is given the ticket id, which the attachment endpoint needs' do + expect(attachment.ticket_id).to eq(42) + end + + it 'is given the article id' do + expect(attachment.article_id).to eq(9) + end + + it 'returns an empty list when the article has no attachments' do + bare = ZammadAPI::Resources::TicketArticle.from_response(transport, id: 9) + expect(bare.attachments).to eq([]) + end + end + + describe '#download' do + subject(:attachment) { described_class.new(transport, id: 3, ticket_id: 42, article_id: 9) } + + it 'requests the attachment endpoint' do + stub = stub_request(:get, download_url).to_return(status: 200, body: 'contents') + attachment.download + expect(stub).to have_been_requested + end + + it 'returns the file contents' do + stub_request(:get, download_url).to_return(status: 200, body: 'contents') + expect(attachment.download).to eq('contents') + end + + it 'uses binary encoding' do + stub_request(:get, download_url).to_return(status: 200, body: 'contents') + expect(attachment.download.encoding).to eq(Encoding::BINARY) + end + + it 'raises when the attachment is gone' do + stub_request(:get, download_url).to_return(json_response({ error: 'not found' }, status: 404)) + expect { attachment.download }.to raise_error(ZammadAPI::NotFoundError) + end + + it 'raises a helpful error when the metadata is incomplete' do + expect { described_class.new(transport, id: 3).download }.to raise_error(KeyError) + end + + it 'escapes a traversal in an id instead of reaching another endpoint' do + stub = stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/ticket_attachment/1%2F..%2F..%2F..%2Fapi%2Fv1%2Fusers/9/3") + .to_return(status: 200, body: 'contents') + escaping = described_class.new(transport, id: 3, ticket_id: '1/../../../api/v1/users', article_id: 9) + + escaping.download + + expect(stub).to have_been_requested + expect(a_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/9/3")).not_to have_been_made + end + end + + it 'is read-only' do + attachment = described_class.new(transport, id: 3) + expect { attachment.filename = 'other.txt' }.to raise_error(NoMethodError, /read-only/) + end + + describe '#inspect' do + it 'summarizes the attachment' do + attachment = described_class.new(transport, id: 3, filename: 'note.txt', size: '12') + expect(attachment.inspect) + .to eq('#') + end + end +end diff --git a/spec/unit/zammad_api/resources/ticket_spec.rb b/spec/unit/zammad_api/resources/ticket_spec.rb new file mode 100644 index 00000000..f9f58da9 --- /dev/null +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -0,0 +1,119 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Resources::Ticket do + subject(:ticket) { described_class.from_response(unit_transport, id: 42, title: 'Help') } + + let(:articles_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/42" } + let(:article_url) { "#{ClientHelper::BASE_URL}api/v1/ticket_articles" } + + describe '#articles' do + it 'requests the articles of this ticket' do + stub = stub_request(:get, articles_url).with(query: { 'expand' => 'true' }).to_return(json_response([])) + ticket.articles + expect(stub).to have_been_requested + end + + it 'returns article records' do + stub_request(:get, articles_url).with(query: hash_including({})) + .to_return(json_response([{ id: 1, body: 'first' }, { id: 2, body: 'second' }])) + + expect(ticket.articles.map(&:body)).to eq(%w[first second]) + end + + it 'returns persisted articles' do + stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response([{ id: 1 }])) + + expect(ticket.articles.first).to be_persisted + end + + it 'raises ParseError when the response is not a list' do + stub_request(:get, articles_url).with(query: hash_including({})).to_return(json_response({ id: 1 })) + + expect { ticket.articles } + .to raise_error(ZammadAPI::ParseError, 'expected a JSON array, got Hash') + end + + it 'says to save an unsaved ticket rather than requesting a path without an id' do + unsaved = described_class.new(unit_transport, title: 'Help') + + expect { unsaved.articles }.to raise_error(ZammadAPI::Error, /Ticket has no id, save it first/) + end + + it 'escapes a traversal in the id instead of reaching another endpoint' do + escaped = "#{ClientHelper::BASE_URL}api/v1/ticket_articles/by_ticket/1%2F..%2F..%2Fusers" + stub = stub_request(:get, escaped).with(query: hash_including({})).to_return(json_response([])) + + described_class.from_response(unit_transport, id: '1/../../users').articles + + expect(stub).to have_been_requested + end + end + + describe '#add_article' do + it 'creates the article for this ticket' do + stub = stub_request(:post, article_url) + .with(query: { 'expand' => 'true' }, body: '{"body":"hello","ticket_id":42}') + .to_return(json_response({ id: 9, body: 'hello', ticket_id: 42 }, status: 201)) + + ticket.add_article(body: 'hello') + expect(stub).to have_been_requested + end + + it 'returns the created article' do + stub_request(:post, article_url).with(query: hash_including({})) + .to_return(json_response({ id: 9, body: 'hello' }, status: 201)) + + expect(ticket.add_article(body: 'hello')).to be_a(ZammadAPI::Resources::TicketArticle) + end + + # `ticket.add_article(params.require(:article).permit(:body))`, which is + # taken apart here before the article is built from it. + it 'reads strong parameters as the Hash they convert to' do + stub = stub_request(:post, article_url) + .with(query: { 'expand' => 'true' }, body: '{"body":"hello","ticket_id":42}') + .to_return(json_response({ id: 9, body: 'hello', ticket_id: 42 }, status: 201)) + + ticket.add_article(StrongParameters.new(body: 'hello')) + expect(stub).to have_been_requested + end + + it 'uses its own id over a ticket_id in the attributes' do + stub = stub_request(:post, article_url) + .with(query: { 'expand' => 'true' }, body: '{"ticket_id":42,"body":"hello"}') + .to_return(json_response({ id: 9, ticket_id: 42 }, status: 201)) + + ticket.add_article(ticket_id: 9, body: 'hello') + expect(stub).to have_been_requested + end + + context 'when the ticket has not been saved' do + subject(:ticket) { described_class.new(unit_transport, title: 'Help') } + + it 'refuses locally' do + expect { ticket.add_article(body: 'hello') }.to raise_error(ZammadAPI::Error, /has no id, save it first/) + end + end + end + + describe 'an article given with the ticket' do + let(:tickets_url) { "#{ClientHelper::BASE_URL}api/v1/tickets" } + + it 'is sent inside the ticket that is created' do + stub = stub_request(:post, tickets_url) + .with(query: { 'expand' => 'true' }, body: { title: 'Help', article: { body: 'It broke.', type: 'note' } }) + .to_return(json_response({ id: 43, title: 'Help' }, status: 201)) + + unit_client.tickets.create(title: 'Help', article: { body: 'It broke.', type: 'note' }) + expect(stub).to have_been_requested + end + + it 'is sent with the update it is staged for' do + stub = stub_request(:put, "#{tickets_url}/42") + .with(query: { 'expand' => 'true' }, body: { state: 'closed', article: { body: 'Done.', type: 'note' } }) + .to_return(json_response({ id: 42, title: 'Help', state: 'closed' })) + + ticket.update(state: 'closed', article: { body: 'Done.', type: 'note' }) + expect(stub).to have_been_requested + end + end +end diff --git a/spec/unit/zammad_api/response_error_spec.rb b/spec/unit/zammad_api/response_error_spec.rb new file mode 100644 index 00000000..bf15f884 --- /dev/null +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -0,0 +1,154 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::ResponseError do + def response(status, body, headers = {}) + ZammadAPI::Response.new( + status: status, + headers: headers, + body: body, + raw_body: body.is_a?(String) ? body : JSON.generate(body) + ) + end + + describe 'hierarchy' do + { + ZammadAPI::ConfigurationError => ZammadAPI::Error, + ZammadAPI::UnknownResourceError => ZammadAPI::Error, + ZammadAPI::ParseError => ZammadAPI::Error, + ZammadAPI::PaginationError => ZammadAPI::Error, + ZammadAPI::ConnectionError => ZammadAPI::TransportError, + ZammadAPI::TimeoutError => ZammadAPI::TransportError, + ZammadAPI::ClientError => described_class, + ZammadAPI::ServerError => described_class, + ZammadAPI::AuthenticationError => ZammadAPI::ClientError, + ZammadAPI::AuthorizationError => ZammadAPI::ClientError, + ZammadAPI::NotFoundError => ZammadAPI::ClientError, + ZammadAPI::ValidationError => ZammadAPI::ClientError, + ZammadAPI::RateLimitError => ZammadAPI::ClientError + }.each do |error_class, parent| + it "#{error_class} descends from #{parent}" do + expect(error_class.ancestors).to include(parent) + end + end + + it 'roots every error at ZammadAPI::Error' do + expect(ZammadAPI::TransportError.ancestors).to include(ZammadAPI::Error) + end + + it 'roots ZammadAPI::Error at StandardError' do + expect(ZammadAPI::Error.ancestors).to include(StandardError) + end + end + + describe '.build' do + { + 401 => ZammadAPI::AuthenticationError, + 403 => ZammadAPI::AuthorizationError, + 404 => ZammadAPI::NotFoundError, + 422 => ZammadAPI::ValidationError, + 429 => ZammadAPI::RateLimitError, + 400 => ZammadAPI::ClientError, + 500 => ZammadAPI::ServerError + }.each do |status, error_class| + it "maps #{status} to #{error_class}" do + result = described_class.build(response(status, {}), 'GET api/v1/users/1') + expect(result).to be_an_instance_of(error_class) + end + end + end + + describe '#message' do + it "uses the body's error key" do + error = described_class.build(response(404, { error: 'User not found' }), 'GET api/v1/users/1') + expect(error.message).to eq('GET api/v1/users/1 failed: User not found') + end + + it 'prefers error_human, which Zammad intends for end users' do + error = described_class.build( + response(422, { error: 'Validation failed', error_human: 'Name is required' }), + 'POST api/v1/groups' + ) + expect(error.message).to eq('POST api/v1/groups failed: Name is required') + end + + it 'falls back to the status when the body is not JSON' do + error = described_class.build(response(502, 'Bad Gateway'), 'GET api/v1/users/1') + expect(error.message).to eq('GET api/v1/users/1 failed: HTTP 502') + end + + it 'falls back to the status when the body has no error key' do + error = described_class.build(response(400, { foo: 'bar' }), 'GET api/v1/users/1') + expect(error.message).to eq('GET api/v1/users/1 failed: HTTP 400') + end + + it 'falls back to the status when the error value is empty' do + error = described_class.build(response(500, { error: '' }), 'GET api/v1/users/1') + expect(error.message).to eq('GET api/v1/users/1 failed: HTTP 500') + end + + it 'is the message alone without a response' do + expect(ZammadAPI::NotFoundError.new('no ZammadAPI::Resources::User matched email').message) + .to eq('no ZammadAPI::Resources::User matched email') + end + end + + describe 'accessors' do + subject(:error) do + described_class.build(response(404, { error: 'nope' }, 'x-request-id' => 'abc'), 'GET api/v1/users/1') + end + + it 'exposes the status' do + expect(error.status).to eq(404) + end + + it 'exposes the decoded body' do + expect(error.body).to eq({ error: 'nope' }) + end + + it 'exposes the headers' do + expect(error.headers).to eq('x-request-id' => 'abc') + end + + it 'exposes the server message' do + expect(error.server_message).to eq('nope') + end + + it 'returns nil accessors without a response' do + bare = described_class.new('nothing matched') + expect([bare.status, bare.body, bare.headers, bare.server_message]).to eq([nil, nil, {}, nil]) + end + + it 'reports the status its class is the name for, without a response' do + bare = ZammadAPI::NotFoundError.new('nothing matched') + expect(bare.status).to eq(404) + end + end + + describe ZammadAPI::RateLimitError do + def retry_after(value) + headers = value.nil? ? {} : { 'retry-after' => value } + + ZammadAPI::ResponseError.build(response(429, {}, headers), 'GET api/v1/users/1').retry_after + end + + it 'exposes Retry-After as an integer' do + expect(retry_after('30')).to eq(30) + end + + it 'returns nil when the header is absent' do + expect(retry_after(nil)).to be_nil + end + + it 'returns nil when the header is not a number' do + expect(retry_after('later')).to be_nil + end + + it 'reads a figure with a zero in front in base ten' do + expect(%w[010 08 0030].map { retry_after(it) }).to eq([10, 8, 30]) + end + + it 'reads a figure held as an Integer' do + expect(retry_after(30)).to eq(30) + end + end +end diff --git a/spec/unit/zammad_api/response_spec.rb b/spec/unit/zammad_api/response_spec.rb new file mode 100644 index 00000000..a182f8b7 --- /dev/null +++ b/spec/unit/zammad_api/response_spec.rb @@ -0,0 +1,76 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Response do + def build(status: 200, body: { a: 1 }, raw_body: '{"a":1}', headers: {}) + described_class.new(status: status, headers: headers, body: body, raw_body: raw_body) + end + + describe '#success?' do + [200, 201, 204, 299].each do |status| + it "is true for #{status}" do + expect(build(status: status)).to be_success + end + end + + [199, 300, 400, 500].each do |status| + it "is false for #{status}" do + expect(build(status: status)).not_to be_success + end + end + end + + describe '.decode_body' do + it 'decodes a JSON body with symbol keys' do + expect(described_class.decode_body('application/json; charset=utf-8', '{"a":{"b":1}}')).to eq(a: { b: 1 }) + end + + it 'leaves a body of another content type as it is' do + expect(described_class.decode_body('text/html', '{"a":1}')).to eq('{"a":1}') + end + + it 'leaves a body as it is when there is no content type' do + expect(described_class.decode_body(nil, '{"a":1}')).to eq('{"a":1}') + end + + it 'leaves an empty JSON body as it is' do + expect(described_class.decode_body('application/json', '')).to eq('') + end + + it 'leaves a JSON body that does not parse as it is' do + expect(described_class.decode_body('application/json', '{"id":')).to eq('{"id":') + end + end + + describe '#decoded' do + it 'returns an object body when one is expected' do + expect(build(body: { a: 1 }).decoded(:object)).to eq(a: 1) + end + + it 'returns an array body when one is expected' do + expect(build(body: [{ a: 1 }]).decoded(:array)).to eq([{ a: 1 }]) + end + + it 'raises when an object was expected but a list arrived' do + expect { build(body: []).decoded(:object) } + .to raise_error(ZammadAPI::ParseError, 'expected a JSON object, got Array') + end + + it 'raises when a list was expected but an object arrived' do + expect { build(body: {}).decoded(:array) } + .to raise_error(ZammadAPI::ParseError, 'expected a JSON array, got Hash') + end + + it 'raises when the body was never JSON' do + expect { build(body: '', raw_body: '').decoded(:object) } + .to raise_error(ZammadAPI::ParseError, /got String/) + end + + it 'accepts an empty list' do + expect(build(body: []).decoded(:array)).to eq([]) + end + end + + it 'is immutable' do + expect(build).to be_frozen + end +end diff --git a/spec/unit/zammad_api/transport_spec.rb b/spec/unit/zammad_api/transport_spec.rb new file mode 100644 index 00000000..62d613b0 --- /dev/null +++ b/spec/unit/zammad_api/transport_spec.rb @@ -0,0 +1,575 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI::Transport do + let(:url) { "#{ClientHelper::BASE_URL}api/v1/groups" } + + describe 'authentication' do + it 'sends a Token header for an access token' do + stub = stub_request(:get, url).with(headers: { 'Authorization' => 'Token test-token' }).to_return(json_response([])) + unit_transport.get('api/v1/groups') + expect(stub).to have_been_requested + end + + it 'sends a Bearer header for an OAuth2 token' do + stub = stub_request(:get, url).with(headers: { 'Authorization' => 'Bearer oauth' }).to_return(json_response([])) + unit_transport(http_token: nil, oauth2_token: 'oauth').get('api/v1/groups') + expect(stub).to have_been_requested + end + + it 'sends basic auth for user and password' do + stub = stub_request(:get, url).with(basic_auth: %w[u p]).to_return(json_response([])) + unit_transport(http_token: nil, user: 'u', password: 'p').get('api/v1/groups') + expect(stub).to have_been_requested + end + end + + describe 'default headers' do + it 'identifies the client' do + stub = stub_request(:get, url) + .with(headers: { 'User-Agent' => "zammad_api-ruby/#{ZammadAPI::VERSION}" }) + .to_return(json_response([])) + unit_transport.get('api/v1/groups') + expect(stub).to have_been_requested + end + + it 'asks for JSON' do + stub = stub_request(:get, url).with(headers: { 'Accept' => 'application/json' }).to_return(json_response([])) + unit_transport.get('api/v1/groups') + expect(stub).to have_been_requested + end + + it 'allows overriding the user agent' do + stub = stub_request(:get, url).with(headers: { 'User-Agent' => 'my-app/1.0' }).to_return(json_response([])) + unit_transport(user_agent: 'my-app/1.0').get('api/v1/groups') + expect(stub).to have_been_requested + end + end + + describe 'request headers' do + it 'sends the headers given for a request, each value as text' do + stub = stub_request(:get, url).with(headers: { 'X-Trace' => 'abc', 'X-Count' => '2' }).to_return(json_response([])) + unit_transport.get('api/v1/groups', headers: { 'X-Trace' => 'abc', 'X-Count' => 2 }) + expect(stub).to have_been_requested + end + end + + describe 'base url handling' do + it 'keeps a sub-path prefix in front of the request path' do + stub = stub_request(:get, 'http://zammad.test/helpdesk/api/v1/groups').to_return(json_response([])) + unit_transport(url: 'http://zammad.test/helpdesk').get('api/v1/groups') + expect(stub).to have_been_requested + end + end + + describe 'query parameters' do + it 'encodes scalars as strings' do + stub = stub_request(:get, url).with(query: { 'page' => '1', 'expand' => 'true' }).to_return(json_response([])) + unit_transport.get('api/v1/groups', query: { page: 1, expand: true }) + expect(stub).to have_been_requested + end + end + + describe '.relative_path' do + it 'drops a leading slash' do + expect(described_class.relative_path('/api/v1/tickets')).to eq('api/v1/tickets') + end + + # Faraday would send the request, credentials and all, to that host. + it 'refuses an absolute URL' do + expect { described_class.relative_path('https://other.example/collect') } + .to raise_error(ArgumentError, /this one is an absolute URL: pass the path alone/) + end + + it 'makes no request for one' do + expect { unit_transport.get('https://other.example/collect') }.to raise_error(ArgumentError) + expect(a_request(:any, //)).not_to have_been_made + end + end + + # The path is printed in the log and in the message of every failed + # request, and a raw request may carry its query in it. + describe '.redact_path' do + it 'leaves a path without a query as it is' do + expect(described_class.redact_path('api/v1/tickets/1')).to eq('api/v1/tickets/1') + end + + it 'drops a query string, which may carry a token' do + expect(described_class.redact_path('api/v1/x?page=2&token=s3cret')).to eq('api/v1/x') + end + + it 'drops a fragment' do + expect(described_class.redact_path('api/v1/x#token=s3cret')).to eq('api/v1/x') + end + end + + describe '.redact' do + it 'blanks the value under a key that names a credential' do + expect(described_class.redact({ login: 'x', password: 'hunter2' })).to eq({ login: 'x', password: '[REDACTED]' }) + end + + it 'reads a String key the way it reads a Symbol' do + expect(described_class.redact({ 'api_key' => 'k' })).to eq({ 'api_key' => '[REDACTED]' }) + end + + it 'blanks one at any depth, through Hashes and Arrays' do + expect(described_class.redact({ users: [{ preferences: { access_token: 't', locale: 'de' } }] })) + .to eq({ users: [{ preferences: { access_token: '[REDACTED]', locale: 'de' } }] }) + end + + it 'blanks the whole of a structure held under such a key' do + expect(described_class.redact({ tokens: [{ name: 'a' }] })).to eq({ tokens: '[REDACTED]' }) + end + + it 'leaves what it was given as it was' do + attributes = { password: 'hunter2' } + described_class.redact(attributes) + + expect(attributes).to eq({ password: 'hunter2' }) + end + + it 'hands back anything that is not a structure' do + expect(described_class.redact('password')).to eq('password') + end + + # One key per alternative of SENSITIVE_KEY_PATTERN, which nothing else in it matches. + %w[password pwd bind_pw passphrase client_secret access_token credentials Cookie Proxy-Authorization privateKey otp_code pw_salt].each do |name| + it "redacts #{name}" do + expect(described_class.redact({ name => 's3cret' })).to eq({ name => '[REDACTED]' }) + end + end + + it 'leaves bind_user alone' do + expect(described_class.redact({ 'bind_user' => 'shown' })).to eq({ 'bind_user' => 'shown' }) + end + end + + describe '.escape_path_segment' do + it 'leaves an ordinary id alone' do + expect(described_class.escape_path_segment(42)).to eq('42') + end + + it 'encodes a separator, so an id cannot walk out of its segment' do + expect(described_class.escape_path_segment('1/../../api/v1/users/1')) + .to eq('1%2F..%2F..%2Fapi%2Fv1%2Fusers%2F1') + end + + it 'encodes a query and fragment marker' do + expect(described_class.escape_path_segment('1?a=b#c')).to eq('1%3Fa%3Db%23c') + end + + it 'encodes a multibyte character one byte at a time' do + expect(described_class.escape_path_segment('ä')).to eq('%C3%A4') + end + + it 'encodes a percent sign rather than passing an encoded id on' do + expect(described_class.escape_path_segment('%2F')).to eq('%252F') + end + + it 'takes a Symbol, for a member that is named rather than numbered' do + expect(described_class.escape_path_segment(:me)).to eq('me') + end + + it 'raises for an id with nothing to send' do + expect { described_class.escape_path_segment('') }.to raise_error(ArgumentError, 'a record id is required') + end + + it 'raises for nil' do + expect { described_class.escape_path_segment(nil) }.to raise_error(ArgumentError, 'a record id is required') + end + end + + describe 'request bodies' do + it 'sends JSON with the matching content type' do + stub = stub_request(:post, url) + .with(body: '{"name":"Support"}', headers: { 'Content-Type' => 'application/json' }) + .to_return(json_response({ id: 1 }, status: 201)) + unit_transport.post('api/v1/groups', body: { name: 'Support' }) + expect(stub).to have_been_requested + end + + it 'sends a body that is already a string as it is' do + stub = stub_request(:post, url) + .with(body: '{"name":"Raw"}', headers: { 'Content-Type' => 'application/json' }) + .to_return(json_response({ id: 1 }, status: 201)) + unit_transport.post('api/v1/groups', body: '{"name":"Raw"}') + expect(stub).to have_been_requested + end + end + + describe 'response decoding' do + it 'decodes JSON with symbol keys' do + stub_request(:get, url).to_return(json_response({ id: 1, nested: { a: 'b' } })) + response = unit_transport.get('api/v1/groups') + expect(response.body).to eq({ id: 1, nested: { a: 'b' } }) + end + + it 'exposes the raw body as well' do + stub_request(:get, url).to_return(json_response({ id: 1 })) + response = unit_transport.get('api/v1/groups') + expect(response.raw_body).to eq('{"id":1}') + end + + it 'downcases header names' do + stub_request(:get, url).to_return(json_response([], headers: { 'X-Request-Id' => 'abc' })) + response = unit_transport.get('api/v1/groups') + expect(response.headers['x-request-id']).to eq('abc') + end + end + + describe 'error responses' do + it 'raises NotFoundError for 404' do + stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) + expect { unit_transport.get('api/v1/groups') } + .to raise_error(ZammadAPI::NotFoundError, 'GET api/v1/groups failed: nope') + end + end + + describe 'network failures' do + it 'wraps a read timeout' do + stub_request(:get, url).to_raise(Net::ReadTimeout) + expect { unit_transport.get('api/v1/groups') } + .to raise_error(ZammadAPI::TimeoutError, %r{\AGET api/v1/groups timed out}) + end + + it 'keeps a query string written into the path out of the message' do + stub_request(:get, url).with(query: hash_including({})).to_raise(Net::ReadTimeout) + expect { unit_transport.get('api/v1/groups?token=path-s3cret') } + .to raise_error(ZammadAPI::TimeoutError, %r{GET api/v1/groups timed out}) { |error| expect(error.message).not_to include('s3cret') } + end + + # Net::HTTP raises Net::OpenTimeout for it, and the default adapter wraps + # that into Faraday::ConnectionFailed with every other failure to connect. + context 'when the connection is not established within open_timeout' do + before { stub_request(:get, url).to_raise(Net::OpenTimeout.new('execution expired')) } + + it 'is still retried, as a read that never reached the server' do + expect { unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups') } + .to raise_error(ZammadAPI::ConnectionError) + expect(a_request(:get, url)).to have_been_made.times(3) + end + end + + it 'wraps a refused connection' do + stub_request(:get, url).to_raise(Errno::ECONNREFUSED) + expect { unit_transport.get('api/v1/groups') } + .to raise_error(ZammadAPI::ConnectionError, %r{\AGET api/v1/groups failed: http://zammad.test/ is unreachable}) + end + + it 'wraps a TLS failure' do + stub_request(:get, url).to_raise(OpenSSL::SSL::SSLError) + expect { unit_transport.get('api/v1/groups') } + .to raise_error(ZammadAPI::ConnectionError, /TLS handshake/) + end + end + + describe 'retries' do + it 'retries an idempotent request after a server error' do + stub_request(:get, url).to_return({ status: 500 }, json_response([{ id: 1 }])) + response = unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups') + expect(response.status).to eq(200) + end + + it 'retries after a rate limit response' do + stub_request(:get, url).to_return({ status: 429 }, json_response([])) + response = unit_transport(retries: 1, retry_interval: 0.01).get('api/v1/groups') + expect(response.status).to eq(200) + end + + # The retry middleware sleeps for whatever Retry-After says, up to a + # ceiling that is set to the timeout. + context 'when the server asks for a longer wait than the timeout' do + let(:transport) { unit_transport(retries: 2, retry_interval: 0.01, timeout: 2) } + + before do + stub_request(:get, url).to_return({ status: 429, headers: { 'Retry-After' => '3600' } }, json_response([])) + end + + it 'does not retry' do + expect { transport.get('api/v1/groups') }.to raise_error(ZammadAPI::RateLimitError) + expect(a_request(:get, url)).to have_been_made.once + end + end + + it 'gives up after the configured number of attempts' do + stub_request(:get, url).to_return(status: 500) + expect { unit_transport(retries: 1, retry_interval: 0.01).get('api/v1/groups') } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:get, url)).to have_been_made.twice + end + + it 'does not retry POST, which could duplicate records' do + stub_request(:post, url).to_return(status: 500) + expect { unit_transport(retries: 2, retry_interval: 0.01).post('api/v1/groups', body: { a: 1 }) } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:post, url)).to have_been_made.once + end + + # A ticket update carrying an article creates that article, and sends its + # e-mail, on every delivery. + it 'does not retry PUT, which Zammad does not always handle idempotently' do + stub_request(:put, "#{url}/1").to_return({ status: 504 }, json_response({ id: 1 })) + expect { unit_transport(retries: 2, retry_interval: 0.01).put('api/v1/groups/1', body: { a: 1 }) } + .to raise_error(ZammadAPI::ServerError) + expect(a_request(:put, "#{url}/1")).to have_been_made.once + end + + # Repeated after a lost answer, a DELETE meets a 404 for the record it has + # just deleted. + it 'does not retry DELETE, which would answer a lost success with a 404' do + stub_request(:delete, "#{url}/1").to_raise(Net::ReadTimeout).then.to_return(json_response({ error: 'gone' }, status: 404)) + expect { unit_transport(retries: 2, retry_interval: 0.01).delete('api/v1/groups/1') } + .to raise_error(ZammadAPI::TimeoutError) + expect(a_request(:delete, "#{url}/1")).to have_been_made.once + end + + it 'does not retry a client error' do + stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) + expect { unit_transport(retries: 2, retry_interval: 0.01).get('api/v1/groups') } + .to raise_error(ZammadAPI::NotFoundError) + expect(a_request(:get, url)).to have_been_made.once + end + end + + describe 'the Faraday seam' do + it 'calls the middleware with the connection being built' do + seen = nil + unit_transport(middleware: ->(connection) { seen = connection }) + + expect(seen).to be_a(Faraday::Connection) + end + + it 'lets the middleware see a request this gem built' do + stub_request(:get, url).to_return(json_response([])) + + seen = nil + transport = unit_transport(middleware: lambda { |builder| + builder.use(Class.new(Faraday::Middleware) do + define_method(:on_request) { |env| seen = env.request_headers['User-Agent'] } + end) + }) + transport.get('api/v1/groups') + + expect(seen).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + end + + it 'hands the timeouts, the TLS setting and the proxy to the connection' do + stub_request(:get, url).to_return(json_response([])) + + seen = nil + transport = unit_transport( + timeout: 7, open_timeout: 3, ssl_verify: false, proxy: 'http://proxy.test:8080', + middleware: lambda { |builder| + builder.use(Class.new(Faraday::Middleware) { define_method(:on_request) { |env| seen = env } }) + } + ) + transport.get('api/v1/groups') + + expect(seen.request.to_h).to include(timeout: 7, open_timeout: 3) + expect(seen.ssl.verify).to be(false) + expect(seen.request.proxy.uri.to_s).to eq('http://proxy.test:8080') + end + + it 'uses the configured adapter' do + transport = unit_transport(adapter: :test) + expect(transport.instance_variable_get(:@connection).adapter.name).to include('Adapter::Test') + end + + # The callable runs after the adapter option is applied, and setting an + # adapter replaces the one that is there. + context 'with an adapter chosen inside the middleware callable' do + let(:stubs) { Faraday::Adapter::Test::Stubs.new { it.get('/api/v1/groups') { [200, { 'Content-Type' => 'application/json' }, '[{"id":7}]'] } } } + + it 'takes it over the one the adapter option names' do + transport = unit_transport(adapter: :net_http, middleware: ->(faraday) { faraday.adapter :test, stubs }) + + expect(transport.get('api/v1/groups').body).to eq([{ id: 7 }]) + expect(a_request(:any, /zammad\.test/)).not_to have_been_made + end + end + + it 'reports an unregistered adapter as a configuration error' do + expect { unit_transport(adapter: :nonsense) } + .to raise_error(ZammadAPI::ConfigurationError, /\Aconfig could not be used to build a connection: .*is not registered on Faraday::Adapter/) + end + end + + describe '#with_on_behalf_of' do + it 'sends the From header' do + stub = stub_request(:get, url).with(headers: { 'From' => 'agent@example.com' }).to_return(json_response([])) + unit_transport.with_on_behalf_of('agent@example.com').get('api/v1/groups') + expect(stub).to have_been_requested + end + + it 'leaves the original transport unscoped' do + transport = unit_transport + transport.with_on_behalf_of('someone') + expect(transport.on_behalf_of).to be_nil + end + + it 'shares the underlying connection instead of rebuilding it' do + transport = unit_transport + scoped = transport.with_on_behalf_of('someone') + expect(scoped.instance_variable_get(:@connection)).to be(transport.instance_variable_get(:@connection)) + end + end + + # Left to Ruby, inspect would print the Faraday connection, whose proxy + # options carry the proxy password and whose middleware stack carries the + # token it was built with. + describe '#inspect' do + let(:transport) do + unit_transport(http_token: 'tok-s3cret', proxy: 'http://puser:pproxy-s3cret@proxy.test:8080') + end + + it 'names the instance and the authentication scheme' do + expect(unit_transport.inspect).to eq('#') + end + + it 'names an on_behalf_of scope' do + expect(unit_transport.with_on_behalf_of('agent@example.com').inspect).to include('on_behalf_of="agent@example.com"') + end + + it 'does not print the access token' do + expect(transport.inspect).not_to include('tok-s3cret') + end + end + + describe '#with_config' do + it 'applies the new configuration' do + expect(unit_transport.with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))).config.timeout).to eq(7) + end + + it 'carries the on_behalf_of scope over' do + derived = unit_transport.with_on_behalf_of('agent@example.com') + .with_config(ZammadAPI::Config.new(**unit_config(timeout: 7))) + + expect(derived.on_behalf_of).to eq('agent@example.com') + end + end + + describe 'logging' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:logger) { Logger.new(log_device, level: Logger::DEBUG) } + + before do + stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) + unit_transport(logger: logger, user: 'u', password: 'pw-s3cret', http_token: nil) + .post('api/v1/groups', body: { login: 'jane', password: 'pw-s3cret' }) + end + + it 'logs the request' do + expect(log).to include('Zammad API request: POST api/v1/groups') + end + + it 'logs the response status' do + expect(log).to include('Zammad API response: POST api/v1/groups -> 201') + end + + it 'never logs a password from the payload' do + expect(log).not_to include('pw-s3cret') + end + + it 'marks the redacted payload value' do + expect(log).to include('password: "[REDACTED]"') + end + + it 'keeps non-sensitive payload values' do + expect(log).to include('login: "jane"') + end + + it 'stays silent by default' do + stub_request(:get, url).to_return(json_response([])) + + expect { unit_transport.get('api/v1/groups') } + .to output('').to_stdout.and output('').to_stderr + end + + # Redaction goes by key, and a String has none. + context 'with a body handed over as a String' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:transport) { unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)) } + + before { stub_request(:post, url).to_return(json_response({ id: 1 }, status: 201)) } + + it 'does not log it, and says how much was left out' do + transport.post('api/v1/groups', body: '{"login":"jane","password":"string-s3cret"}') + + expect(log).not_to include('string-s3cret') + expect(log).to include('Zammad API payload: [43 bytes, not logged]') + end + end + + context 'with a query that carries a credential' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:transport) { unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)) } + + before { stub_request(:get, url).with(query: hash_including({})).to_return(json_response([])) } + + it 'redacts it by key' do + transport.get('api/v1/groups', query: { page: 1, token: 'query-s3cret' }) + + expect(log).to include('Zammad API request: GET api/v1/groups query={page: 1, token: "[REDACTED]"}') + end + end + + # A raw request may carry its query in the path, where there is no key + # to redact it by. + context 'with a query string written into the path' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + let(:verify) { 'api/v1/users/password_reset_verify?token=path-s3cret&locale=de' } + + before do + stub_request(:get, "#{ClientHelper::BASE_URL}api/v1/users/password_reset_verify").with(query: hash_including({})).to_return(json_response({})) + unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).get(verify) + end + + it 'keeps the credential in it out of the log' do + expect(log).not_to include('path-s3cret') + end + + it 'logs the request line without it' do + expect(log).to include("Zammad API request: GET api/v1/users/password_reset_verify\n") + end + + it 'logs the response line without it' do + expect(log).to include('Zammad API response: GET api/v1/users/password_reset_verify -> 200') + end + end + + # A raw request takes headers of its own and the request line prints them. + context 'with credential-bearing headers' do + subject(:log) { log_device.string } + + let(:log_device) { StringIO.new } + + before do + stub_request(:get, url).to_return(json_response([])) + unit_transport(logger: Logger.new(log_device, level: Logger::DEBUG)).get( + 'api/v1/groups', + headers: { + 'Cookie' => '_zammad_session=cookie-s3cret', + 'Proxy-Authorization' => 'Basic proxy-s3cret', + 'X-CSRF-Token' => 'csrf-s3cret', + 'X-Request-Id' => 'request-123' + } + ) + end + + it 'marks the redacted header' do + expect(log).to include('"Cookie" => "[REDACTED]"') + end + + it 'keeps a header that carries no credential' do + expect(log).to include('"X-Request-Id" => "request-123"') + end + end + end +end diff --git a/spec/zammad_api/client_spec.rb b/spec/zammad_api/client_spec.rb deleted file mode 100644 index 9f6b73ff..00000000 --- a/spec/zammad_api/client_spec.rb +++ /dev/null @@ -1,110 +0,0 @@ -require 'spec_helper' -require 'logger' - -describe ZammadAPI::Client do - before(:all) do - WebMock.enable! - end - - after(:all) do - WebMock.disable! - end - - after do - WebMock.reset! - end - - let(:config) { Helper.config } - let(:instance) { described_class.new(config) } - - describe '.new' do - it 'raises ConfigurationError when url is missing' do - expect { described_class.new(config.merge(url: nil)) } - .to raise_error(ZammadAPI::ConfigurationError, 'missing url in config') - end - - it 'raises ConfigurationError when url scheme is unsupported' do - expect { described_class.new(config.merge(url: 'ftp://example.com')) } - .to raise_error(ZammadAPI::ConfigurationError, 'config url needs to start with http:// or https://') - end - - it 'raises ConfigurationError when user is missing' do - expect { described_class.new(config.merge(user: nil)) } - .to raise_error(ZammadAPI::ConfigurationError, 'missing user in config') - end - - it 'raises ConfigurationError when password is missing' do - expect { described_class.new(config.merge(password: nil)) } - .to raise_error(ZammadAPI::ConfigurationError, 'missing password in config') - end - - it 'does not require user/password when http_token is supplied' do - expect { described_class.new(url: config[:url], http_token: 'token') }.not_to raise_error - end - - it 'does not require user/password when oauth2_token is supplied' do - expect { described_class.new(url: config[:url], oauth2_token: 'token') }.not_to raise_error - end - end - - describe '#method_missing' do - it 'raises ResourceNotFoundError for unknown resources' do - expect { instance.does_not_exist }.to raise_error(ZammadAPI::ResourceNotFoundError, /Resource for DoesNotExist does not exist/) - end - - it 'attaches the underlying NameError as #cause' do - instance.does_not_exist - rescue ZammadAPI::ResourceNotFoundError => e - expect(e.cause).to be_a(NameError) - end - end - - describe '#perform_on_behalf_of' do - it 'performs a given block on behalft of a given user' do - on_behalf_of_identifier = 'some_login' - - stub_request(:get, /#{config[:url]}/) - .with(headers: { - 'From' => on_behalf_of_identifier - }) - .to_return(status: 200, body: '{}', headers: {}) - - instance.perform_on_behalf_of(on_behalf_of_identifier) do - instance.user.find(1) - end - end - - it "doesn't affect later requests outside of the block" do - # first perform request on behalf of a login - on_behalf_of_identifier = 'some_login' - - stub_request(:get, /#{config[:url]}/) - .with(headers: { - 'From' => on_behalf_of_identifier - }) - .to_return(status: 200, body: '{}', headers: {}) - - instance.perform_on_behalf_of(on_behalf_of_identifier) do - instance.user.find(1) - end - - # now without and check that - # the header isn't set anymore - stub = stub_request(:get, /#{config[:url]}/) - .to_return(status: 200, body: '{}', headers: {}) - - # this is kind of a hack/workaround to check if the - # header was not set/send since webmock doesn't support - # checks for not existing headers - request_pattern = stub.request_pattern - def request_pattern.matches?(request_signature) - return false if !super - return true if request_signature.headers.empty? - - !request_signature.headers.key?('From') - end - - instance.user.find(1) - end - end -end diff --git a/spec/zammad_api/errors_spec.rb b/spec/zammad_api/errors_spec.rb deleted file mode 100644 index b3350886..00000000 --- a/spec/zammad_api/errors_spec.rb +++ /dev/null @@ -1,164 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI do - describe ZammadAPI::Error do - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe ZammadAPI::ConfigurationError do - it 'descends from ZammadAPI::Error' do - expect(described_class.ancestors).to include(ZammadAPI::Error) - end - - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe ZammadAPI::ResourceNotFoundError do - it 'descends from ZammadAPI::Error' do - expect(described_class.ancestors).to include(ZammadAPI::Error) - end - - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe ZammadAPI::ResponseError do - let(:fake_response) { Struct.new(:status, :body) } - - describe '.from' do - it 'returns a ClientError for 4xx responses' do - response = fake_response.new(404, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ClientError) - end - - it 'returns a ClientError for 408 (Request Timeout)' do - response = fake_response.new(408, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ClientError) - end - - it 'returns a ClientError for 429 (Too Many Requests)' do - response = fake_response.new(429, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ClientError) - end - - it 'returns a ServerError for 5xx responses' do - response = fake_response.new(500, '{}') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ServerError) - end - - it 'returns a ServerError for 502 (Bad Gateway)' do - response = fake_response.new(502, 'Bad Gateway') - expect(described_class.from(response, operation: 'find object')).to be_a(ZammadAPI::ServerError) - end - - it 'returns a base ResponseError when no response is supplied' do - result = described_class.from(nil, operation: 'find object') - expect(result.class).to eq(described_class) - end - end - - describe 'subclasses' do - it 'ClientError descends from ResponseError' do - expect(ZammadAPI::ClientError.ancestors).to include(described_class) - end - - it 'ServerError descends from ResponseError' do - expect(ZammadAPI::ServerError.ancestors).to include(described_class) - end - - it 'descends from ZammadAPI::Error' do - expect(described_class.ancestors).to include(ZammadAPI::Error) - end - - it 'descends from RuntimeError' do - expect(described_class.ancestors).to include(RuntimeError) - end - end - - describe '#message' do - it "uses the JSON body's 'error' key when present" do - response = fake_response.new(404, '{"error":"User not found"}') - error = described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): User not found") - end - - it 'preserves the original message format for the JSON-with-error case' do - response = fake_response.new(422, '{"error":"name can\'t be blank"}') - error = described_class.from(response, operation: 'save object', resource_class: ZammadAPI::Resources::Group) - expect(error.message).to eq("Can't save object (ZammadAPI::Resources::Group): name can't be blank") - end - - it 'falls back to HTTP status when the body is not JSON (issue #29 scenario)' do - response = fake_response.new(502, 'Bad Gateway') - error = described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): HTTP 502") - end - - it 'falls back to HTTP status when the body is empty' do - response = fake_response.new(500, '') - error = described_class.from(response, operation: 'destroy object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't destroy object (ZammadAPI::Resources::User): HTTP 500") - end - - it "falls back to HTTP status when the JSON body has no 'error' key" do - response = fake_response.new(400, '{"foo":"bar"}') - error = described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - expect(error.message).to eq("Can't find object (ZammadAPI::Resources::User): HTTP 400") - end - - it 'omits the resource_class segment when none is supplied' do - response = fake_response.new(404, '{"error":"nope"}') - error = described_class.from(response, operation: 'find object') - expect(error.message).to eq("Can't find object: nope") - end - - it 'does not attach the JSON parser error as cause (it is a symptom, not the cause)' do - response = fake_response.new(502, 'Bad Gateway') - error = described_class.from(response, operation: 'find object') - expect(error.cause).to be_nil - end - end - - describe 'accessors' do - let(:response) { fake_response.new(404, '{"error":"nope"}') } - let(:error) do - described_class.from(response, operation: 'find object', resource_class: ZammadAPI::Resources::User) - end - - it 'exposes the underlying response' do - expect(error.response).to be(response) - end - - it 'exposes the response status' do - expect(error.status).to eq(404) - end - - it 'exposes the response body' do - expect(error.body).to eq('{"error":"nope"}') - end - - it 'exposes the operation' do - expect(error.operation).to eq('find object') - end - - it 'exposes the resource_class' do - expect(error.resource_class).to eq(ZammadAPI::Resources::User) - end - - it 'returns nil for status when no response is supplied' do - error = described_class.from(nil, operation: 'find object') - expect(error.status).to be_nil - end - - it 'returns nil for body when no response is supplied' do - error = described_class.from(nil, operation: 'find object') - expect(error.body).to be_nil - end - end - end -end diff --git a/spec/zammad_api/json_helper_spec.rb b/spec/zammad_api/json_helper_spec.rb deleted file mode 100644 index 29eb9567..00000000 --- a/spec/zammad_api/json_helper_spec.rb +++ /dev/null @@ -1,21 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI::JsonHelper do - subject(:helper) do - Class.new { include ZammadAPI::JsonHelper }.new - end - - describe '#safe_json_parse' do - it 'parses valid JSON' do - expect(helper.safe_json_parse('{"key":"value"}')).to eq('key' => 'value') - end - - it 'returns empty hash for invalid JSON' do - expect(helper.safe_json_parse('not json')).to eq({}) - end - - it 'returns empty hash for HTML responses' do - expect(helper.safe_json_parse('Bad Gateway')).to eq({}) - end - end -end diff --git a/spec/zammad_api/resources/group_spec.rb b/spec/zammad_api/resources/group_spec.rb deleted file mode 100644 index 6caf0d3b..00000000 --- a/spec/zammad_api/resources/group_spec.rb +++ /dev/null @@ -1,154 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI, 'group object basics' do - client = Helper.client - - name = "some_group#{Helper.random}" - group = nil - - it 'new with invalid attributes' do - group_invalid = client.group.new - - expect(group_invalid.class).to eq(ZammadAPI::Resources::Group) - expect(group_invalid.new_record?).to be(true) - - expect { group_invalid.save }.to raise_error(ZammadAPI::ClientError) - end - - it 'new with valid attributes' do - group = client.group.new( - name: name, - assignment_timeout: 100, - follow_up_assignment: false, - follow_up_possible: 'yes', - note: '', - active: true, - ) - - expect(group.class).to eq(ZammadAPI::Resources::Group) - expect(group.new_record?).to be(true) - expect(group.id).to be_nil - expect(group.name).to eq(name) - expect(group.assignment_timeout).to eq(100) - expect(group.follow_up_assignment).to be(false) - expect(group.follow_up_possible).to eq('yes') - expect(group.note).to eq('') - expect(group.active).to be(true) - end - - it 'save' do - result = group.save - - expect(result).to be(true) - expect(group.id).not_to be_nil - expect(group.name).to eq(name) - expect(group.assignment_timeout).to eq(100) - expect(group.follow_up_assignment).to be(false) - expect(group.follow_up_possible).to eq('yes') - expect(group.note).to eq('') - expect(group.active).to be(true) - - group.name = "#{name}-2" - group.note = 'some note' - group.assignment_timeout = 4711 - group.active = false - - changes = group.changes - expect(changes.key?(:follow_up_possible)).to be(false) - expect(changes[:name][0]).to eq(name) - expect(changes[:name][1]).to eq("#{name}-2") - expect(changes[:assignment_timeout][0]).to eq(100) - expect(changes[:assignment_timeout][1]).to eq(4711) - expect(changes[:note][0]).to eq('') - expect(changes[:note][1]).to eq('some note') - expect(changes[:active][0]).to be(true) - expect(changes[:active][1]).to be(false) - - result = group.save - expect(result).to be(true) - expect(group.id).to be_a(Integer) - expect(group.name).to eq("#{name}-2") - expect(group.assignment_timeout).to eq(4711) - expect(group.follow_up_assignment).to be(false) - expect(group.follow_up_possible).to eq('yes') - expect(group.note).to eq('some note') - expect(group.active).to be(false) - end - - it 'find' do - group_lookup = client.group.find(group.id) - - expect(group_lookup.class).to eq(ZammadAPI::Resources::Group) - expect(group_lookup.id).to eq(group.id) - expect(group_lookup.name).to eq("#{name}-2") - expect(group_lookup.assignment_timeout).to eq(4711) - expect(group_lookup.follow_up_assignment).to be(false) - expect(group_lookup.follow_up_possible).to eq('yes') - expect(group_lookup.note).to eq('some note') - expect(group_lookup.active).to be(false) - end - - it 'all' do - groups = client.group.all - - group_exists = nil - groups.each do |local_group| - next if local_group.id != group.id - - group_exists = local_group - end - expect(group_exists.class).to eq(ZammadAPI::Resources::Group) - expect(group_exists.id).to eq(group.id) - expect(group_exists.name).to eq("#{name}-2") - expect(group_exists.assignment_timeout).to eq(4711) - expect(group_exists.follow_up_assignment).to be(false) - expect(group_exists.follow_up_possible).to eq('yes') - expect(group_exists.note).to eq('some note') - expect(group_exists.active).to be(false) - - group_exists.active = true - group_exists.save - - group_lookup = client.group.find(group.id) - expect(group_lookup.class).to eq(ZammadAPI::Resources::Group) - expect(group_lookup.id).to eq(group.id) - expect(group_lookup.name).to eq("#{name}-2") - expect(group_lookup.assignment_timeout).to eq(4711) - expect(group_lookup.follow_up_assignment).to be(false) - expect(group_lookup.follow_up_possible).to eq('yes') - expect(group_lookup.note).to eq('some note') - expect(group_lookup.active).to be(true) - end - - it 'pagination with all' do - groups = client.group.all - - expect(groups[0].class).to eq(ZammadAPI::Resources::Group) - - count = 0 - groups.each do |local_group| - expect(local_group.class).to eq(ZammadAPI::Resources::Group) - count += 1 - end - expect(count).to eq(3) - - count = 0 - groups = client.group.all - groups.page(1, 3) do |local_group| - expect(local_group.class).to eq(ZammadAPI::Resources::Group) - count += 1 - end - expect(count).to eq(3) - groups.page(2, 3) do |local_group| - expect(local_group.class).to eq(ZammadAPI::Resources::Group) - count += 1 - end - expect(count).to eq(3) - end - - it 'destroy' do - result = group.destroy - - expect(result).to be(true) - end -end diff --git a/spec/zammad_api/resources/list_base_spec.rb b/spec/zammad_api/resources/list_base_spec.rb deleted file mode 100644 index c7018e34..00000000 --- a/spec/zammad_api/resources/list_base_spec.rb +++ /dev/null @@ -1,7 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI::ListBase do - it 'is a Enumerable' do - expect(described_class.ancestors).to include(Enumerable) - end -end diff --git a/spec/zammad_api/resources/organization_spec.rb b/spec/zammad_api/resources/organization_spec.rb deleted file mode 100644 index 78511811..00000000 --- a/spec/zammad_api/resources/organization_spec.rb +++ /dev/null @@ -1,215 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI, 'organization object basics' do - client = Helper.client - - name = "some_organization#{Helper.random}" - organization = nil - - it 'new with invalid attributes' do - organization_invalid = client.organization.new - - expect(organization_invalid.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_invalid.new_record?).to be(true) - - expect { organization_invalid.save }.to raise_error(ZammadAPI::ClientError) - end - - it 'new with valid attributes' do - organization = client.organization.new( - name: name, - shared: false, - note: '', - active: true, - ) - - expect(organization.class).to eq(ZammadAPI::Resources::Organization) - expect(organization.new_record?).to be(true) - expect(organization.id).to be_nil - expect(organization.name).to eq(name) - expect(organization.shared).to be(false) - expect(organization.note).to eq('') - expect(organization.active).to be(true) - end - - it 'save' do - result = organization.save - - expect(result).to be(true) - expect(organization.id).not_to be_nil - expect(organization.name).to eq(name) - expect(organization.shared).to be(false) - expect(organization.note).to eq('') - expect(organization.active).to be(true) - expect(organization.created_by).to eq('admin@example.com') - expect(organization.updated_by).to eq('admin@example.com') - - organization.name = "#{name}-2" - organization.note = 'some note' - organization.shared = true - organization.active = false - - changes = organization.changes - expect(changes.key?(:not_existing)).to be(false) - expect(changes[:name][0]).to eq(name) - expect(changes[:name][1]).to eq("#{name}-2") - expect(changes[:shared][0]).to be(false) - expect(changes[:shared][1]).to be(true) - expect(changes[:note][0]).to eq('') - expect(changes[:note][1]).to eq('some note') - expect(changes[:active][0]).to be(true) - expect(changes[:active][1]).to be(false) - - result = organization.save - expect(result).to be(true) - expect(organization.id).to be_a(Integer) - expect(organization.name).to eq("#{name}-2") - expect(organization.shared).to be(true) - expect(organization.note).to eq('some note') - expect(organization.active).to be(false) - expect(organization.created_by).to eq('admin@example.com') - expect(organization.updated_by).to eq('admin@example.com') - end - - it 'find' do - organization_lookup = client.organization.find(organization.id) - - expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_lookup.id).to eq(organization.id) - expect(organization_lookup.name).to eq("#{name}-2") - expect(organization_lookup.shared).to be(true) - expect(organization_lookup.note).to eq('some note') - expect(organization_lookup.active).to be(false) - expect(organization_lookup.created_by).to eq('admin@example.com') - expect(organization_lookup.updated_by).to eq('admin@example.com') - end - - it 'all' do - organizations = client.organization.all - - organization_exists = nil - organizations.each do |local_organization| - next if local_organization.id != organization.id - - organization_exists = local_organization - end - expect(organization_exists.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_exists.id).to eq(organization.id) - expect(organization_exists.name).to eq("#{name}-2") - expect(organization_exists.note).to eq('some note') - expect(organization_exists.active).to be(false) - expect(organization_exists.created_by).to eq('admin@example.com') - expect(organization_exists.updated_by).to eq('admin@example.com') - - organization_exists.active = true - organization_exists.save - - organization_lookup = client.organization.find(organization.id) - expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_lookup.id).to eq(organization.id) - expect(organization_lookup.name).to eq("#{name}-2") - expect(organization_lookup.note).to eq('some note') - expect(organization_lookup.active).to be(true) - expect(organization_lookup.created_by).to eq('admin@example.com') - expect(organization_lookup.updated_by).to eq('admin@example.com') - end - - it 'pagination with all' do - organizations = client.organization.all - - expect(organizations[0].class).to eq(ZammadAPI::Resources::Organization) - - count = 0 - organizations.each do |local_organization| - expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) - count += 1 - end - expect(count).to eq(2) - - count = 0 - organizations = client.organization.all - organizations.page(1, 3) do |local_organization| - expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) - count += 1 - end - expect(count).to eq(2) - organizations.page(2, 3) do |local_organization| - expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) - count += 1 - end - expect(count).to eq(2) - end - - it 'search' do - organizations = client.organization.search(query: name) - - organization_exists = nil - organizations.each do |local_organization| - next if local_organization.id != organization.id - - organization_exists = local_organization - end - expect(organization_exists.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_exists.id).to eq(organization.id) - expect(organization_exists.name).to eq("#{name}-2") - expect(organization_exists.note).to eq('some note') - expect(organization_exists.active).to be(true) - expect(organization_exists.created_by).to eq('admin@example.com') - expect(organization_exists.updated_by).to eq('admin@example.com') - - organization_exists.active = false - organization_exists.save - - organization_lookup = client.organization.find(organization.id) - expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_lookup.id).to eq(organization.id) - expect(organization_lookup.name).to eq("#{name}-2") - expect(organization_lookup.note).to eq('some note') - expect(organization_lookup.active).to be(false) - expect(organization_lookup.created_by).to eq('admin@example.com') - expect(organization_lookup.updated_by).to eq('admin@example.com') - end - - it 'pagination with search' do - organizations = client.organization.search(query: "#{name}-2") - - expect(organizations[0].class).to eq(ZammadAPI::Resources::Organization) - - count = 0 - organization_exists = nil - organizations.each do |local_organization| - expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) - count += 1 - next if local_organization.id != organization.id - - organization_exists = local_organization - end - expect(count).to eq(1) - expect(organization_exists.class).to eq(ZammadAPI::Resources::Organization) - expect(organization_exists.id).to eq(organization.id) - expect(organization_exists.name).to eq("#{name}-2") - expect(organization_exists.note).to eq('some note') - expect(organization_exists.active).to be(false) - expect(organization_exists.created_by).to eq('admin@example.com') - expect(organization_exists.updated_by).to eq('admin@example.com') - - count = 0 - organizations = client.organization.search(query: 'zammad') - organizations.page(1, 3) do |local_organization| - expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) - count += 1 - end - expect(count).to eq(1) - organizations.page(2, 3) do |local_organization| - expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) - count += 1 - end - expect(count).to eq(1) - end - - it 'destroy' do - result = organization.destroy - - expect(result).to be(true) - end -end diff --git a/spec/zammad_api/resources/ticket_priority_spec.rb b/spec/zammad_api/resources/ticket_priority_spec.rb deleted file mode 100644 index 45f41a80..00000000 --- a/spec/zammad_api/resources/ticket_priority_spec.rb +++ /dev/null @@ -1,135 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI, 'ticket priority object basics' do - client = Helper.client - - name = "some_ticket_priority#{Helper.random}" - ticket_priority = nil - - it 'new with invalid attributes' do - ticket_priority_invalid = client.ticket_priority.new - - expect(ticket_priority_invalid.class).to eq(ZammadAPI::Resources::TicketPriority) - expect(ticket_priority_invalid.new_record?).to be(true) - - expect { ticket_priority_invalid.save }.to raise_error(ZammadAPI::ClientError) - end - - it 'new with valid attributes' do - ticket_priority = client.ticket_priority.new( - name: name, - note: '', - active: true, - ) - - expect(ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) - expect(ticket_priority.new_record?).to be(true) - expect(ticket_priority.id).to be_nil - expect(ticket_priority.name).to eq(name) - expect(ticket_priority.note).to eq('') - expect(ticket_priority.active).to be(true) - end - - it 'save' do - result = ticket_priority.save - - expect(result).to be(true) - expect(ticket_priority.id).not_to be_nil - expect(ticket_priority.name).to eq(name) - expect(ticket_priority.note).to eq('') - expect(ticket_priority.active).to be(true) - - ticket_priority.name = "#{name}-2" - ticket_priority.note = 'some note' - ticket_priority.active = false - - changes = ticket_priority.changes - expect(changes.key?(:not_existing)).to be(false) - expect(changes[:name][0]).to eq(name) - expect(changes[:name][1]).to eq("#{name}-2") - expect(changes[:note][0]).to eq('') - expect(changes[:note][1]).to eq('some note') - expect(changes[:active][0]).to be(true) - expect(changes[:active][1]).to be(false) - - result = ticket_priority.save - expect(result).to be(true) - expect(ticket_priority.id).to be_a(Integer) - expect(ticket_priority.name).to eq("#{name}-2") - expect(ticket_priority.note).to eq('some note') - expect(ticket_priority.active).to be(false) - end - - it 'find' do - ticket_priority_lookup = client.ticket_priority.find(ticket_priority.id) - - expect(ticket_priority_lookup.class).to eq(ZammadAPI::Resources::TicketPriority) - expect(ticket_priority_lookup.id).to eq(ticket_priority.id) - expect(ticket_priority_lookup.name).to eq("#{name}-2") - expect(ticket_priority_lookup.note).to eq('some note') - expect(ticket_priority_lookup.active).to be(false) - end - - it 'all' do - ticket_priorities = client.ticket_priority.all - - ticket_priority_exists = nil - ticket_priorities.each do |local_ticket_priority| - next if local_ticket_priority.id != ticket_priority.id - - ticket_priority_exists = local_ticket_priority - end - expect(ticket_priority_exists.class).to eq(ZammadAPI::Resources::TicketPriority) - expect(ticket_priority_exists.id).to eq(ticket_priority.id) - expect(ticket_priority_exists.name).to eq("#{name}-2") - expect(ticket_priority_exists.note).to eq('some note') - expect(ticket_priority_exists.active).to be(false) - - ticket_priority_exists.active = true - ticket_priority_exists.save - - ticket_priority_lookup = client.ticket_priority.find(ticket_priority.id) - expect(ticket_priority_lookup.class).to eq(ZammadAPI::Resources::TicketPriority) - expect(ticket_priority_lookup.id).to eq(ticket_priority.id) - expect(ticket_priority_lookup.name).to eq("#{name}-2") - expect(ticket_priority_lookup.note).to eq('some note') - expect(ticket_priority_lookup.active).to be(true) - end - - it 'pagination with all' do - ticket_priorities = client.ticket_priority.all - - expect(ticket_priorities[0].class).to eq(ZammadAPI::Resources::TicketPriority) - - count = 0 - ticket_priorities.each do |local_ticket_priority| - expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) - count += 1 - end - expect(count).to eq(4) - - count = 0 - ticket_priorities = client.ticket_priority.all - ticket_priorities.page(1, 2) do |local_ticket_priority| - expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) - count += 1 - end - expect(count).to eq(2) - ticket_priorities.page(2, 2) do |local_ticket_priority| - expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) - count += 1 - end - expect(count).to eq(4) - ticket_priorities.page(3, 2) do |local_ticket_priority| - expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) - count += 1 - end - expect(count).to eq(4) - end - - it 'destroy' do - result = ticket_priority.destroy - - expect(result).to be(true) - end -end diff --git a/spec/zammad_api/resources/ticket_spec.rb b/spec/zammad_api/resources/ticket_spec.rb deleted file mode 100644 index 1c957058..00000000 --- a/spec/zammad_api/resources/ticket_spec.rb +++ /dev/null @@ -1,223 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI, 'ticket object basics' do - client = Helper.client - - title = "some ticket title ##{Helper.random}" - ticket = nil - - it 'new with invalid attributes' do - ticket_invalid = client.ticket.new - - expect(ticket_invalid.class).to eq(ZammadAPI::Resources::Ticket) - expect(ticket_invalid.new_record?).to be(true) - - expect { ticket_invalid.save }.to raise_error(ZammadAPI::ClientError) - end - - it 'new with valid attributes' do - ticket = client.ticket.new( - title: title, - state: 'new', - priority: '2 normal', - owner: '-', - customer: 'nicole.braun@zammad.org', - group: 'Users', - article: { - sender: 'Customer', - type: 'note', - subject: 'some subject', - content_type: 'text/plain', - body: 'some body', - } - ) - - expect(ticket.class).to eq(ZammadAPI::Resources::Ticket) - expect(ticket.new_record?).to be(true) - expect(ticket.id).to be_nil - expect(ticket.title).to eq(title) - expect(ticket.state).to eq('new') - expect(ticket.group).to eq('Users') - expect(ticket.owner).to eq('-') - end - - it 'save' do - result = ticket.save - - expect(result).to be(true) - expect(ticket.new_record?).to be(false) - expect(ticket.id).not_to be_nil - expect(ticket.title).to eq(title) - expect(ticket.state).to eq('new') - expect(ticket.state_id).to eq(1) - expect(ticket.owner).to eq('-') - expect(ticket.owner_id).to eq(1) - expect(ticket.created_by).to eq('admin@example.com') - expect(ticket.updated_by).to eq('admin@example.com') - - ticket.title = "#{title}-2" - ticket.state = 'open' - - changes = ticket.changes - expect(changes.key?(:state_id)).to be(false) - expect(changes.key?(:state)).to be(true) - expect(changes[:title][0]).to eq(title) - expect(changes[:title][1]).to eq("#{title}-2") - expect(changes[:state][0]).to eq('new') - expect(changes[:state][1]).to eq('open') - - result = ticket.save - expect(result).to be(true) - expect(ticket.new_record?).to be(false) - expect(ticket.id).to be_a(Integer) - expect(ticket.title).to eq("#{title}-2") - expect(ticket.state).to eq('open') - expect(ticket.state_id).to eq(2) - expect(ticket.owner).to eq('-') - expect(ticket.owner_id).to eq(1) - expect(ticket.created_by).to eq('admin@example.com') - expect(ticket.updated_by).to eq('admin@example.com') - - articles = ticket.articles - expect(articles.length).to eq(1) - expect(articles[0].class).to eq(ZammadAPI::Resources::TicketArticle) - expect(articles[0].subject).to eq('some subject') - expect(articles[0].body).to eq('some body') - - ticket.article( - subject: 'some subject2', - body: 'some body2', - ) - - articles = ticket.articles - expect(articles.length).to eq(2) - expect(articles[1].class).to eq(ZammadAPI::Resources::TicketArticle) - expect(articles[1].subject).to eq('some subject2') - expect(articles[1].body).to eq('some body2') - expect(articles[1].attachments.count).to eq(0) - - ticket.article( - subject: 'some subject3', - body: 'some body3', - attachments: [ - { - 'filename' => 'some_file.txt', - 'data' => 'dGVzdCAxMjM=', - 'mime-type' => 'text/plain' - }, - ] - ) - - articles = ticket.articles - expect(articles.length).to eq(3) - expect(articles[2].class).to eq(ZammadAPI::Resources::TicketArticle) - expect(articles[2].subject).to eq('some subject3') - expect(articles[2].body).to eq('some body3') - expect(articles[2].attachments.count).to eq(1) - expect(articles[2].attachments[0].filename).to eq('some_file.txt') - expect(articles[2].attachments[0].download).to eq('test 123') - expect(articles[2].attachments[0].size).to eq('8') - expect(articles[2].attachments[0].preferences[:'Mime-Type']).to eq('text/plain') - end - - it 'find' do - ticket_lookup = client.ticket.find(ticket.id) - - expect(ticket_lookup.class).to eq(ZammadAPI::Resources::Ticket) - expect(ticket_lookup.id).to eq(ticket.id) - expect(ticket_lookup.title).to eq("#{title}-2") - expect(ticket_lookup.state).to eq('open') - expect(ticket_lookup.state_id).to eq(2) - expect(ticket_lookup.owner).to eq('-') - expect(ticket_lookup.owner_id).to eq(1) - expect(ticket_lookup.created_by).to eq('admin@example.com') - expect(ticket_lookup.updated_by).to eq('admin@example.com') - end - - it 'all' do - tickets = client.ticket.all - - ticket_exists = nil - tickets.each do |local_ticket| - next if local_ticket.id != ticket.id - - ticket_exists = local_ticket - end - expect(ticket_exists.class).to eq(ZammadAPI::Resources::Ticket) - expect(ticket_exists.id).to eq(ticket.id) - expect(ticket_exists.title).to eq("#{title}-2") - expect(ticket_exists.state).to eq('open') - expect(ticket_exists.state_id).to eq(2) - expect(ticket_exists.owner).to eq('-') - expect(ticket_exists.owner_id).to eq(1) - expect(ticket_exists.created_by).to eq('admin@example.com') - expect(ticket_exists.updated_by).to eq('admin@example.com') - - ticket_exists.state = 'closed' - ticket_exists.save - - ticket_lookup = client.ticket.find(ticket.id) - expect(ticket_lookup.class).to eq(ZammadAPI::Resources::Ticket) - expect(ticket_lookup.id).to eq(ticket.id) - expect(ticket_lookup.title).to eq("#{title}-2") - expect(ticket_lookup.state).to eq('closed') - expect(ticket_lookup.state_id).to eq(4) - expect(ticket_lookup.owner).to eq('-') - expect(ticket_lookup.owner_id).to eq(1) - expect(ticket_lookup.created_by).to eq('admin@example.com') - expect(ticket_lookup.updated_by).to eq('admin@example.com') - end - - it 'pagination with all' do - (1..10).each do |local_count| - client.ticket.create( - title: "test count ticket #{local_count}", - state: 'new', - priority: '2 normal', - owner: '-', - customer: 'nicole.braun@zammad.org', - group: 'Users', - article: { - sender: 'Customer', - type: 'note', - subject: 'some subject', - content_type: 'text/plain', - body: 'some body', - } - ) - end - - tickets = client.ticket.all - expect(tickets[0].class).to eq(ZammadAPI::Resources::Ticket) - count = 0 - tickets.each do |local_ticket| - expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) - count += 1 - end - expect(count).to eq(12) - - count = 0 - tickets = client.ticket.all - tickets.page(1, 5) do |local_ticket| - expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) - count += 1 - end - expect(count).to eq(5) - tickets.page(2, 5) do |local_ticket| - expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) - count += 1 - end - expect(count).to eq(10) - tickets.page(3, 5) do |local_ticket| - expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) - count += 1 - end - expect(count).to eq(12) - end - - it 'destroy' do - result = ticket.destroy - - expect(result).to be(true) - end -end diff --git a/spec/zammad_api/resources/ticket_state_spec.rb b/spec/zammad_api/resources/ticket_state_spec.rb deleted file mode 100644 index d6723982..00000000 --- a/spec/zammad_api/resources/ticket_state_spec.rb +++ /dev/null @@ -1,185 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI, 'ticket state object basics' do - client = Helper.client - - name = "some_ticket_state#{Helper.random}" - ticket_state = nil - - it 'new with invalid attributes' do - ticket_state_invalid = client.ticket_state.new - - expect(ticket_state_invalid.class).to eq(ZammadAPI::Resources::TicketState) - expect(ticket_state_invalid.new_record?).to be(true) - - expect { ticket_state_invalid.save }.to raise_error(ZammadAPI::ClientError) - end - - it 'new with valid attributes' do - ticket_state = client.ticket_state.new( - name: name, - state_type: 'new', - next_state_id: nil, - ignore_escalation: false, - note: '', - active: true, - ) - - expect(ticket_state.class).to eq(ZammadAPI::Resources::TicketState) - expect(ticket_state.new_record?).to be(true) - expect(ticket_state.id).to be_nil - expect(ticket_state.name).to eq(name) - expect(ticket_state.state_type).to eq('new') - expect(ticket_state.state_type_id).to be_nil - expect(ticket_state.next_state_id).to be_nil - expect(ticket_state.ignore_escalation).to be(false) - expect(ticket_state.note).to eq('') - expect(ticket_state.active).to be(true) - end - - it 'save' do - result = ticket_state.save - - expect(result).to be(true) - expect(ticket_state.id).not_to be_nil - expect(ticket_state.name).to eq(name) - expect(ticket_state.state_type).to eq('new') - expect(ticket_state.state_type_id).to eq(1) - expect(ticket_state.next_state_id).to be_nil - expect(ticket_state.ignore_escalation).to be(false) - expect(ticket_state.note).to eq('') - expect(ticket_state.active).to be(true) - expect(ticket_state.created_by).to eq('admin@example.com') - expect(ticket_state.updated_by).to eq('admin@example.com') - - ticket_state.name = "#{name}-2" - ticket_state.note = 'some note' - ticket_state.state_type = 'open' - ticket_state.next_state = 'closed' - ticket_state.ignore_escalation = true - ticket_state.active = false - - changes = ticket_state.changes - expect(changes.key?(:next_state_id)).to be(false) - expect(changes.key?(:next_state)).to be(true) - expect(changes[:name][0]).to eq(name) - expect(changes[:name][1]).to eq("#{name}-2") - expect(changes[:state_type][0]).to eq('new') - expect(changes[:state_type][1]).to eq('open') - expect(changes[:next_state][0]).to be_nil - expect(changes[:next_state][1]).to eq('closed') - expect(changes[:ignore_escalation][0]).to be(false) - expect(changes[:ignore_escalation][1]).to be(true) - expect(changes[:note][0]).to eq('') - expect(changes[:note][1]).to eq('some note') - expect(changes[:active][0]).to be(true) - expect(changes[:active][1]).to be(false) - - result = ticket_state.save - expect(result).to be(true) - expect(ticket_state.id).to be_a(Integer) - expect(ticket_state.name).to eq("#{name}-2") - expect(ticket_state.state_type).to eq('open') - expect(ticket_state.state_type_id).to eq(2) - expect(ticket_state.next_state).to eq('closed') - expect(ticket_state.next_state_id).to eq(4) - expect(ticket_state.ignore_escalation).to be(true) - expect(ticket_state.note).to eq('some note') - expect(ticket_state.active).to be(false) - expect(ticket_state.created_by).to eq('admin@example.com') - expect(ticket_state.updated_by).to eq('admin@example.com') - end - - it 'find' do - ticket_state_lookup = client.ticket_state.find(ticket_state.id) - - expect(ticket_state_lookup.class).to eq(ZammadAPI::Resources::TicketState) - expect(ticket_state_lookup.id).to eq(ticket_state.id) - expect(ticket_state_lookup.name).to eq("#{name}-2") - expect(ticket_state_lookup.state_type).to eq('open') - expect(ticket_state_lookup.state_type_id).to eq(2) - expect(ticket_state_lookup.next_state).to eq('closed') - expect(ticket_state_lookup.next_state_id).to eq(4) - expect(ticket_state_lookup.ignore_escalation).to be(true) - expect(ticket_state_lookup.note).to eq('some note') - expect(ticket_state_lookup.active).to be(false) - expect(ticket_state_lookup.created_by).to eq('admin@example.com') - expect(ticket_state_lookup.updated_by).to eq('admin@example.com') - end - - it 'all' do - ticket_states = client.ticket_state.all - - ticket_state_exists = nil - ticket_states.each do |local_ticket_state| - next if local_ticket_state.id != ticket_state.id - - ticket_state_exists = local_ticket_state - end - expect(ticket_state_exists.class).to eq(ZammadAPI::Resources::TicketState) - expect(ticket_state_exists.id).to eq(ticket_state.id) - expect(ticket_state_exists.name).to eq("#{name}-2") - expect(ticket_state_exists.state_type).to eq('open') - expect(ticket_state_exists.state_type_id).to eq(2) - expect(ticket_state_exists.next_state).to eq('closed') - expect(ticket_state_exists.next_state_id).to eq(4) - expect(ticket_state_exists.ignore_escalation).to be(true) - expect(ticket_state_exists.note).to eq('some note') - expect(ticket_state_exists.active).to be(false) - expect(ticket_state_exists.created_by).to eq('admin@example.com') - expect(ticket_state_exists.updated_by).to eq('admin@example.com') - - ticket_state_exists.active = true - ticket_state_exists.save - - ticket_state_lookup = client.ticket_state.find(ticket_state.id) - expect(ticket_state_lookup.class).to eq(ZammadAPI::Resources::TicketState) - expect(ticket_state_lookup.id).to eq(ticket_state.id) - expect(ticket_state_lookup.name).to eq("#{name}-2") - expect(ticket_state_lookup.state_type).to eq('open') - expect(ticket_state_lookup.state_type_id).to eq(2) - expect(ticket_state_lookup.next_state).to eq('closed') - expect(ticket_state_lookup.next_state_id).to eq(4) - expect(ticket_state_lookup.note).to eq('some note') - expect(ticket_state_lookup.active).to be(true) - expect(ticket_state_lookup.created_by).to eq('admin@example.com') - expect(ticket_state_lookup.updated_by).to eq('admin@example.com') - end - - it 'pagination with all' do - ticket_states = client.ticket_state.all - - expect(ticket_states[0].class).to eq(ZammadAPI::Resources::TicketState) - - count = 0 - ticket_states.each do |local_ticket_state| - expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) - count += 1 - end - expect(count).to be >= 7 - - count = 0 - ticket_states = client.ticket_state.all - ticket_states.page(1, 3) do |local_ticket_state| - expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) - count += 1 - end - expect(count).to eq(3) - ticket_states.page(2, 3) do |local_ticket_state| - expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) - count += 1 - end - expect(count).to eq(6) - ticket_states.page(3, 3) do |local_ticket_state| - expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) - count += 1 - end - expect(count).to be >= 7 - end - - it 'destroy' do - result = ticket_state.destroy - - expect(result).to be(true) - end -end diff --git a/spec/zammad_api/resources/user_spec.rb b/spec/zammad_api/resources/user_spec.rb deleted file mode 100644 index a82b94b4..00000000 --- a/spec/zammad_api/resources/user_spec.rb +++ /dev/null @@ -1,275 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI, 'user object basics' do - client = Helper.client - - random = Helper.random - firstname = "firstname#{random}" - lastname = "lastname#{random}" - email = "some_user#{random}@example.com" - user = nil - - it 'new with invalid attributes' do - user_invalid = client.user.new - - expect(user_invalid.class).to eq(ZammadAPI::Resources::User) - expect(user_invalid.new_record?).to be(true) - - expect { user_invalid.save }.to raise_error(ZammadAPI::ClientError) - end - - it 'new with valid attributes' do - user = client.user.new( - firstname: firstname, - lastname: lastname, - email: email, - groups: { - Users: ['full'] - }, - roles: ['Customer'], - preferences: { key1: 123, key2: 'abc' }, - note: '', - active: true, - ) - - expect(user.class).to eq(ZammadAPI::Resources::User) - expect(user.new_record?).to be(true) - expect(user.id).to be_nil - expect(user.firstname).to eq(firstname) - expect(user.lastname).to eq(lastname) - expect(user.email).to eq(email) - expect(user.preferences).to eq({ key1: 123, key2: 'abc' }) - expect(user.note).to eq('') - expect(user.active).to be(true) - end - - it 'save' do - result = user.save - - expect(result).to be(true) - expect(user.id).not_to be_nil - expect(user.firstname).to eq(firstname) - expect(user.lastname).to eq(lastname) - expect(user.email).to eq(email) - expect(user.group_ids).to be_empty - expect(user.groups).to be_empty - expect(user.role_ids).to eq([3]) - expect(user.roles).to eq(['Customer']) - expect(user.preferences).to eq({ key1: 123, key2: 'abc' }) - expect(user.note).to eq('') - expect(user.active).to be(true) - expect(user.created_by).to eq('admin@example.com') - expect(user.updated_by).to eq('admin@example.com') - - user.firstname = "firstname#{random}-2" - user.roles = ['Agent'] - user.note = 'some note' - - changes = user.changes - expect(changes.key?(:lastname)).to be(false) - expect(changes[:firstname][0]).to eq(firstname) - expect(changes[:firstname][1]).to eq("#{firstname}-2") - expect(changes[:note][0]).to eq('') - expect(changes[:note][1]).to eq('some note') - - result = user.save - expect(result).to be(true) - expect(user.id).to be_a(Integer) - expect(user.firstname).to eq("#{firstname}-2") - expect(user.lastname).to eq(lastname) - expect(user.email).to eq(email) - expect(user.group_ids).to eq({ '1': ['full'] }) - expect(user.groups).to eq({ Users: ['full'] }) - expect(user.role_ids).to eq([2]) - expect(user.roles).to eq(['Agent']) - expect(user.note).to eq('some note') - expect(user.created_by).to eq('admin@example.com') - expect(user.updated_by).to eq('admin@example.com') - end - - it 'find' do - user_lookup = client.user.find(user.id) - - expect(user_lookup.class).to eq(ZammadAPI::Resources::User) - expect(user_lookup.id).to eq(user.id) - expect(user_lookup.firstname).to eq("#{firstname}-2") - expect(user_lookup.lastname).to eq(lastname) - expect(user_lookup.email).to eq(email) - expect(user_lookup.group_ids).to eq({ '1': ['full'] }) - expect(user_lookup.groups).to eq({ Users: ['full'] }) - expect(user_lookup.role_ids).to eq([2]) - expect(user_lookup.roles).to eq(['Agent']) - expect(user_lookup.note).to eq('some note') - expect(user_lookup.created_by).to eq('admin@example.com') - expect(user_lookup.updated_by).to eq('admin@example.com') - end - - it 'all' do - users = client.user.all - - user_exists = nil - users.each do |local_user| - next if local_user.id != user.id - - user_exists = local_user - end - expect(user_exists.class).to eq(ZammadAPI::Resources::User) - expect(user_exists.id).to eq(user.id) - expect(user_exists.id).to eq(user.id) - expect(user_exists.firstname).to eq("#{firstname}-2") - expect(user_exists.lastname).to eq(lastname) - expect(user_exists.email).to eq(email) - expect(user_exists.group_ids).to eq({ '1': ['full'] }) - expect(user_exists.groups).to eq({ Users: ['full'] }) - expect(user_exists.role_ids).to eq([2]) - expect(user_exists.roles).to eq(['Agent']) - expect(user_exists.note).to eq('some note') - expect(user_exists.created_by).to eq('admin@example.com') - expect(user_exists.updated_by).to eq('admin@example.com') - user_exists.save - - user_lookup = client.user.find(user.id) - expect(user_lookup.class).to eq(ZammadAPI::Resources::User) - expect(user_lookup.id).to eq(user.id) - expect(user_lookup.firstname).to eq("#{firstname}-2") - expect(user_lookup.lastname).to eq(lastname) - expect(user_lookup.email).to eq(email) - expect(user_lookup.group_ids).to eq({ '1': ['full'] }) - expect(user_lookup.groups).to eq({ Users: ['full'] }) - expect(user_lookup.role_ids).to eq([2]) - expect(user_lookup.roles).to eq(['Agent']) - expect(user_lookup.note).to eq('some note') - expect(user_lookup.active).to be(true) - expect(user_lookup.created_by).to eq('admin@example.com') - expect(user_lookup.updated_by).to eq('admin@example.com') - end - - it 'pagination with all' do - (1..10).each do |local_count| - client.user.create( - firstname: "firstname#{local_count}", - lastname: "lastname#{local_count}", - email: "customer_email#{local_count}@example.com", - groups: { Users: ['full'] }, - roles: ['Customer'], - note: '', - active: true, - ) - end - - users = client.user.all - - expect(users[0].class).to eq(ZammadAPI::Resources::User) - count = 0 - users.each do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - end - expect(count).to eq(15) - - count = 0 - users = client.user.all - users.page(1, 4) do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - end - expect(count).to eq(4) - users.page(2, 5) do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - end - expect(count).to eq(9) - count = 0 - users.page(1, 200) do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - end - expect(count).to eq(15) - end - - it 'search' do - users = client.user.search(query: firstname) - - user_exists = nil - users.each do |local_user| - next if local_user.id != user.id - - user_exists = local_user - end - expect(user_exists.class).to eq(ZammadAPI::Resources::User) - expect(user_exists.id).to eq(user.id) - expect(user_exists.firstname).to eq("#{firstname}-2") - expect(user_exists.group_ids).to eq({ '1': ['full'] }) - expect(user_exists.groups).to eq({ Users: ['full'] }) - expect(user_exists.role_ids).to eq([2]) - expect(user_exists.roles).to eq(['Agent']) - expect(user_exists.active).to be(true) - expect(user_exists.created_by).to eq('admin@example.com') - expect(user_exists.updated_by).to eq('admin@example.com') - - user_exists.active = false - user_exists.save - - user_lookup = client.user.find(user.id) - expect(user_lookup.class).to eq(ZammadAPI::Resources::User) - expect(user_lookup.id).to eq(user.id) - expect(user_lookup.firstname).to eq("#{firstname}-2") - expect(user_lookup.group_ids).to be_empty - expect(user_lookup.groups).to be_empty - expect(user_lookup.role_ids).to eq([2]) - expect(user_lookup.roles).to eq(['Agent']) - expect(user_lookup.active).to be(false) - expect(user_lookup.created_by).to eq('admin@example.com') - expect(user_lookup.updated_by).to eq('admin@example.com') - end - - it 'pagination with search' do - users = client.user.search(query: firstname) - - expect(users[0].class).to eq(ZammadAPI::Resources::User) - - count = 0 - user_exists = nil - users.each do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - next if local_user.id != user.id - - user_exists = local_user - end - expect(count).to eq(1) - expect(user_exists.class).to eq(ZammadAPI::Resources::User) - expect(user_exists.id).to eq(user.id) - expect(user_exists.firstname).to eq("#{firstname}-2") - expect(user_exists.group_ids).to be_empty - expect(user_exists.groups).to be_empty - expect(user_exists.role_ids).to eq([2]) - expect(user_exists.roles).to eq(['Agent']) - expect(user_exists.active).to be(false) - expect(user_exists.created_by).to eq('admin@example.com') - expect(user_exists.updated_by).to eq('admin@example.com') - - count = 0 - users = client.user.search(query: firstname) - users.page(1, 3) do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - end - expect(count).to eq(1) - users.page(2, 3) do |local_user| - expect(local_user.class).to eq(ZammadAPI::Resources::User) - count += 1 - end - expect(count).to eq(1) - end - - it 'destroy' do - # wait until zammad scheduler wrote some entries to activity stream - # to have some references and not allow users to delete - sleep 12 - - expect { user.destroy }.to raise_error(ZammadAPI::ClientError) - #result = user.destroy - #expect(result).to eq(true) - end -end diff --git a/spec/zammad_api/transport_spec.rb b/spec/zammad_api/transport_spec.rb deleted file mode 100644 index 66032e5c..00000000 --- a/spec/zammad_api/transport_spec.rb +++ /dev/null @@ -1,80 +0,0 @@ -require 'spec_helper' -require 'logger' - -describe ZammadAPI::Transport do - before(:all) do - WebMock.enable! - end - - after(:all) do - WebMock.disable! - end - - after do - WebMock.reset! - end - - let(:config) { Helper.config } - let(:logger) do - Logger.new($stderr).tap do |logger| - logger.level = Logger::ERROR - end - end - let(:instance) { described_class.new(config, logger) } - - context 'GET' do - it 'performs GET requests' do - stub_request(:get, "#{config[:url]}some/path") - .to_return(status: 200, body: '', headers: {}) - - instance.get(url: '/some/path') - end - end - - context 'on behalf of' do - it 'responds to #on_behalf_of' do - expect(instance).to respond_to(:on_behalf_of) - end - - it 'responds to #on_behalf_of=' do - expect(instance).to respond_to(:on_behalf_of=) - end - - it 'sets From header' do - on_behalf_of_identifier = 'some_login' - - instance.on_behalf_of = on_behalf_of_identifier - - stub_request(:get, "#{config[:url]}some/path") - .with(headers: { - 'From' => on_behalf_of_identifier - }) - .to_return(status: 200, body: '', headers: {}) - - instance.get(url: '/some/path') - end - - it 'unsets From header' do - on_behalf_of_identifier = 'some_login' - - instance.on_behalf_of = on_behalf_of_identifier - instance.on_behalf_of = nil - - stub = stub_request(:get, "#{config[:url]}some/path") - .to_return(status: 200, body: '', headers: {}) - - # this is kind of a hack/workaround to check if the - # header was not set/send since webmock doesn't support - # checks for not existing headers - request_pattern = stub.request_pattern - def request_pattern.matches?(request_signature) - return false if !super - return true if request_signature.headers.empty? - - !request_signature.headers.key?('From') - end - - instance.get(url: '/some/path') - end - end -end diff --git a/spec/zammad_api_spec.rb b/spec/zammad_api_spec.rb deleted file mode 100644 index 6616717c..00000000 --- a/spec/zammad_api_spec.rb +++ /dev/null @@ -1,36 +0,0 @@ -require 'spec_helper' - -describe ZammadAPI do - it 'has a version number' do - expect(ZammadAPI::VERSION).not_to be_nil - end - - context 'failing authentication' do - Helper.auto_wizard - client = Helper.client(user: 'not_existing', password: 'not_existing') - - it 'user' do - expect { client.user.find(1) }.to raise_error(ZammadAPI::ClientError) do |error| - expect(error.status).to eq(401) - expect(error.operation).to eq('find object') - expect(error.resource_class).to eq(ZammadAPI::Resources::User) - end - end - - it 'organization' do - expect { client.organization.find(1) }.to raise_error(ZammadAPI::ClientError) - end - - it 'group' do - expect { client.group.find(1) }.to raise_error(ZammadAPI::ClientError) - end - - it 'ticket_priority' do - expect { client.ticket_priority.find(1) }.to raise_error(ZammadAPI::ClientError) - end - - it 'ticket_state' do - expect { client.ticket_state.find(1) }.to raise_error(ZammadAPI::ClientError) - end - end -end diff --git a/zammad_api.gemspec b/zammad_api.gemspec index 7b094541..7d9d2513 100644 --- a/zammad_api.gemspec +++ b/zammad_api.gemspec @@ -1,28 +1,55 @@ -lib = File.expand_path('lib', __dir__) -$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) -require 'zammad_api/version' +# frozen_string_literal: true + +require_relative 'lib/zammad_api/version' Gem::Specification.new do |spec| - spec.name = 'zammad_api' - spec.version = ZammadAPI::VERSION.dup - spec.authors = ['Martin Edenhofer', 'Martin Gruner'] - spec.email = ['support@zammad.org'] + spec.name = 'zammad_api' + spec.version = ZammadAPI::VERSION + spec.authors = ['Martin Edenhofer', 'Martin Gruner', 'Mantas Masalskis'] + spec.email = ['support@zammad.org'] - spec.summary = 'Zammad API v1.0 client.' - spec.description = 'Ruby wrapper for the Zammad API v1.0.' - spec.homepage = 'https://github.com/zammad/zammad-api-client-ruby' - spec.licenses = ['AGPL-3.0-only', 'MIT'] - spec.required_ruby_version = '>= 3.0' # Same as TargetRubyVersion in .rubocop.yml. + # v1.0 is the version of the API, the one a Zammad serves under /api/v1, and + # not of this gem. + spec.summary = 'Ruby client for the Zammad API v1.0.' + spec.description = 'Tickets, articles, users, organizations and groups of a Zammad instance as records to ' \ + 'find, create, update and destroy, with collections that paginate themselves, timeouts, ' \ + 'retries and an error class per kind of failure.' + spec.homepage = 'https://github.com/zammad/zammad-api-client-ruby' + spec.licenses = ['AGPL-3.0-only', 'MIT'] - spec.metadata['allowed_push_host'] = 'https://rubygems.org' + # Keep in sync with TargetRubyVersion in .rubocop.yml and the CI matrix. + # + # 3.4 rather than 3.3, which gets security fixes until March 2027, for the + # `it` block parameter that lib/ uses throughout. Nothing else needs 3.4: + # lowering the floor is rewriting `it` to `_1`, the five spec expectations + # of the format Hash#inspect has had since 3.4, and a CI entry. + spec.required_ruby_version = '>= 3.4' - spec.metadata['homepage_uri'] = spec.homepage - spec.metadata['source_code_uri'] = 'https://github.com/zammad/zammad-api-client-ruby' - spec.metadata['changelog_uri'] = 'https://github.com/zammad/zammad-api-client-ruby/blob/master/CHANGELOG.md' - spec.metadata['rubygems_mfa_required'] = 'true' + spec.metadata['allowed_push_host'] = 'https://rubygems.org' + spec.metadata['source_code_uri'] = spec.homepage + spec.metadata['changelog_uri'] = "#{spec.homepage}/blob/master/CHANGELOG.md" + spec.metadata['bug_tracker_uri'] = "#{spec.homepage}/issues" + spec.metadata['documentation_uri'] = "https://rubydoc.info/gems/zammad_api/#{ZammadAPI::VERSION}" + spec.metadata['rubygems_mfa_required'] = 'true' - spec.files = Dir['{lib}/**/*'] - spec.require_paths = ['lib'] + # sig/vendor holds stand-ins for dependencies that ship no signatures. They + # exist only for this repository's own type checking and are not published. + spec.files = Dir['lib/**/*.rb', 'sig/**/*.rbs'].grep_v(%r{\Asig/vendor/}) + %w[ + .yardopts + CHANGELOG.md + LICENSE.AGPL.txt + LICENSE.MIT.txt + LICENSE.md + README.md + UPGRADING.md + ] + spec.require_paths = ['lib'] + spec.extra_rdoc_files = ['README.md', 'UPGRADING.md', 'CHANGELOG.md'] - spec.add_dependency 'faraday', '~> 2' + spec.add_dependency 'faraday', '~> 2.9' + spec.add_dependency 'faraday-retry', '~> 2.2' + # Required by lib/zammad_api/config.rb. From Ruby 4.0 on it is a bundled + # gem, which Bundler makes loadable only where the bundle names it, and + # Faraday names it from 2.10.0 on: a bundle resolved to 2.9 had none. + spec.add_dependency 'logger', '~> 1.5' end From 183c02620d282a2728232bc8d5ae9f9e1372570d Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 1 Dec 2026 18:38:18 +0200 Subject: [PATCH 2/5] Feat: add RBS signatures and check them with Steep The gem ships signatures in sig/, so a typed project gets completion and checking for the client, the collections and the records without writing any of its own. ResourceProxy and Collection are generic over the resource they hold: client.tickets is a ResourceProxy[Resources::Ticket], and what it finds, yields and searches is a Ticket. Each resource declares the attributes Zammad serves for it. Three things keep the signatures honest. rake steep checks lib/ against them. rake rbs_published validates the published set without sig/vendor, which holds stand-ins for dependencies that ship no signatures and is kept out of the gem: a Faraday type named in a published signature would fail for every consumer and pass here. And spec/typed/usage.rb is a file written the way a caller writes one, checked as a second Steep target, where each line that must be a type error carries a steep:ignore. With this commit the default rake task has everything it runs. --- Steepfile | 33 ++++ sig/vendor/faraday.rbs | 51 +++++++ sig/zammad_api.rbs | 3 + sig/zammad_api/attribute_access.rbs | 31 ++++ sig/zammad_api/client.rbs | 42 ++++++ sig/zammad_api/collection.rbs | 46 ++++++ sig/zammad_api/config.rbs | 69 +++++++++ sig/zammad_api/deep_copy.rbs | 7 + sig/zammad_api/errors.rbs | 61 ++++++++ sig/zammad_api/resource_proxy.rbs | 41 +++++ sig/zammad_api/resources/base.rbs | 66 ++++++++ sig/zammad_api/resources/resources.rbs | 201 +++++++++++++++++++++++++ sig/zammad_api/response.rbs | 16 ++ sig/zammad_api/transport.rbs | 47 ++++++ spec/typed/sig/usage.rbs | 32 ++++ spec/typed/usage.rb | 74 +++++++++ 16 files changed, 820 insertions(+) create mode 100644 Steepfile create mode 100644 sig/vendor/faraday.rbs create mode 100644 sig/zammad_api.rbs create mode 100644 sig/zammad_api/attribute_access.rbs create mode 100644 sig/zammad_api/client.rbs create mode 100644 sig/zammad_api/collection.rbs create mode 100644 sig/zammad_api/config.rbs create mode 100644 sig/zammad_api/deep_copy.rbs create mode 100644 sig/zammad_api/errors.rbs create mode 100644 sig/zammad_api/resource_proxy.rbs create mode 100644 sig/zammad_api/resources/base.rbs create mode 100644 sig/zammad_api/resources/resources.rbs create mode 100644 sig/zammad_api/response.rbs create mode 100644 sig/zammad_api/transport.rbs create mode 100644 spec/typed/sig/usage.rbs create mode 100644 spec/typed/usage.rb diff --git a/Steepfile b/Steepfile new file mode 100644 index 00000000..cf8dcb81 --- /dev/null +++ b/Steepfile @@ -0,0 +1,33 @@ +# frozen_string_literal: true + +target :lib do + signature 'sig' + check 'lib' + + # uri is here for the parse Config makes of the instance url and the + # escaping of record ids. The signatures the gem publishes do not name it, + # so this does not add anything a consumer has to load. + library 'json', 'logger', 'uri' + + configure_code_diagnostics do |hash| + # Default keyword-argument hashes such as `attributes = {}` cannot be + # annotated without hurting readability. + hash[Steep::Diagnostic::Ruby::UnannotatedEmptyCollection] = nil + end +end + +# A file written the way a typed project that uses this gem writes one, checked +# against the same signatures as lib/. It is never run - see spec/typed/usage.rb +# for what it pins. +# +# sig/vendor is in here, although a consumer does not have it, because Steep +# hands a signature file to every target of a project whatever the target's +# own pattern says. That the published signatures stand on their own is what +# `rake rbs_published` establishes. +target :usage do + signature 'sig', 'spec/typed/sig' + check 'spec/typed' + + # logger is the one library the published signatures name. + library 'logger' +end diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs new file mode 100644 index 00000000..9db943ed --- /dev/null +++ b/sig/vendor/faraday.rbs @@ -0,0 +1,51 @@ +# Minimal declarations for the parts of Faraday this gem uses. +# Faraday does not ship RBS signatures of its own. + +module Faraday + class Error < StandardError + def initialize: (?untyped exc, ?untyped response) -> void + def response: () -> untyped + end + + class ConnectionFailed < Error + end + + class TimeoutError < Error + end + + class SSLError < Error + end + + class RetriableResponse < Error + end + + class Response + def status: () -> Integer + def body: () -> untyped + def headers: () -> untyped + end + + class Request + def url: (String) -> void + def params: () -> Hash[String, untyped] + def body=: (untyped) -> void + def headers: () -> Hash[String, untyped] + end + + # Faraday.new yields the connection itself, which delegates the stack + # building methods below to its RackBuilder. + class Connection + def get: (String) ?{ (Request) -> void } -> Response + def post: (String) ?{ (Request) -> void } -> Response + def put: (String) ?{ (Request) -> void } -> Response + def delete: (String) ?{ (Request) -> void } -> Response + def public_send: (Symbol, *untyped) ?{ (Request) -> void } -> Response + + def request: (Symbol, *untyped) -> void + def response: (Symbol, *untyped) -> void + def adapter: (untyped, *untyped) -> void + def use: (untyped, *untyped) -> void + end + + def self.new: (**untyped) ?{ (Connection) -> void } -> Connection +end diff --git a/sig/zammad_api.rbs b/sig/zammad_api.rbs new file mode 100644 index 00000000..3a9109a7 --- /dev/null +++ b/sig/zammad_api.rbs @@ -0,0 +1,3 @@ +module ZammadAPI + VERSION: String +end diff --git a/sig/zammad_api/attribute_access.rbs b/sig/zammad_api/attribute_access.rbs new file mode 100644 index 00000000..47eb2170 --- /dev/null +++ b/sig/zammad_api/attribute_access.rbs @@ -0,0 +1,31 @@ +module ZammadAPI + module AttributeAccess + # private_constant in the source; RBS has no way to say so. + ATTRIBUTE_WRITER: Regexp + + @attributes: Hash[Symbol, untyped] + + attr_reader attributes: Hash[Symbol, untyped] + + def []: (Symbol | String key) -> untyped + def []=: (Symbol | String key, untyped value) -> untyped + def fetch: (Symbol | String key, *untyped default) ?{ (Symbol) -> untyped } -> untyped + def key?: (Symbol | String key) -> bool + def to_h: () -> Hash[Symbol, untyped] + def id: () -> Integer? + def deconstruct_keys: (Array[Symbol]?) -> Hash[Symbol, untyped] + def ==: (untyped other) -> bool + def eql?: (untyped other) -> bool + def hash: () -> Integer + def as_json: (*untyped) -> Hash[Symbol, untyped] + def to_json: (*untyped) -> String + def method_missing: (Symbol, *untyped) -> untyped + def respond_to_missing?: (Symbol, ?bool) -> bool + + private + + def writable_attributes?: () -> bool + def write_attribute: (Symbol, untyped) -> untyped + def frozen_attributes: (untyped) -> untyped + end +end diff --git a/sig/zammad_api/client.rbs b/sig/zammad_api/client.rbs new file mode 100644 index 00000000..931759c6 --- /dev/null +++ b/sig/zammad_api/client.rbs @@ -0,0 +1,42 @@ +module ZammadAPI + class Client + RESOURCES: Hash[Symbol, untyped] + ENV_OPTIONS: Hash[String, Symbol] + + @transport: Transport + @resources: Hash[untyped, ResourceProxy[untyped]] + + def self.from_env: (**untyped overrides) -> Client + + def initialize: (?transport: Transport?, **untyped options) -> void + def config: () -> Config + + def groups: () -> ResourceProxy[Resources::Group] + def organizations: () -> ResourceProxy[Resources::Organization] + def tickets: () -> ResourceProxy[Resources::Ticket] + def ticket_articles: () -> ResourceProxy[Resources::TicketArticle] + def ticket_priorities: () -> ResourceProxy[Resources::TicketPriority] + def ticket_states: () -> ResourceProxy[Resources::TicketState] + def users: () -> ResourceProxy[Resources::User] + + # A class cannot carry its own type into the answer - RBS has no way to + # say "a proxy for whichever class this is" - so a proxy for a resource of + # your own is untyped until you say what it is: + # + # roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] + def resource: (Symbol | String | Class name) -> ResourceProxy[untyped] + def resource_names: () -> Array[Symbol] + def me: () -> Resources::User + def version: () -> String? + + def get: (String path, ?query: Hash[untyped, untyped]?, ?headers: Hash[untyped, untyped]?) -> Response + def post: (String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + def put: (String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + def delete: (String path, ?query: Hash[untyped, untyped]?, ?headers: Hash[untyped, untyped]?) -> Response + + def with: (**untyped options) -> Client + def on_behalf_of: (String | Integer identifier) -> Client + | [T] (String | Integer identifier) { (Client) -> T } -> T + def inspect: () -> String + end +end diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs new file mode 100644 index 00000000..e3ffd4d4 --- /dev/null +++ b/sig/zammad_api/collection.rbs @@ -0,0 +1,46 @@ +module ZammadAPI + # Generic over the resource it holds, so that what a walk yields is a + # Resources::Ticket rather than something untyped: `client.tickets.all` is a + # Collection[Resources::Ticket]. + class Collection[R < Resources::Base] + include Enumerable[R] + + SEARCH_MAX_PER_PAGE: Integer + + @transport: Transport + @resource_class: untyped + @path: String + @query: Hash[Symbol, untyped] + @per_page: Integer + @page: Integer? + @search: bool + + def initialize: (Transport transport, untyped resource_class, ?search: bool, ?query: Hash[Symbol, untyped], ?per_page: Integer?, ?page: Integer?) -> void + + def each: () { (R) -> void } -> Collection[R] + | () -> Enumerator[R, Collection[R]] + def find_each: (?batch_size: Integer?) { (R) -> void } -> Collection[R] + | (?batch_size: Integer?) -> Enumerator[R, Collection[R]] + def in_batches: (?of: Integer?) { (Array[R]) -> void } -> Collection[R] + | (?of: Integer?) -> Enumerator[Array[R], Collection[R]] + def page: (Integer number, ?per_page: Integer?) -> Collection[R] + def first: () -> R? + | (Integer count) -> Array[R] + def find: (?untyped ifnone) { (R) -> boolish } -> R? + | (*untyped) -> untyped + def order: (*(Symbol | String) attributes, **(Symbol | String) directions) -> Collection[R] + def pluck: (*(Symbol | String) keys) -> Array[untyped] + def count: (*untyped) ?{ (R) -> boolish } -> Integer + def empty?: () -> bool + def inspect: () -> String + + private + + def walk: () { (Array[R]) -> void } -> void + def fetch: (Integer number) -> Array[R] + def repeated_page_message: (Integer number) -> String + def total_count: () -> Integer? + def sorted_by: () -> Hash[String, String] + def with: (?page: Integer?, ?per_page: Integer?, ?query: Hash[Symbol, untyped]) -> Collection[R] + end +end diff --git a/sig/zammad_api/config.rbs b/sig/zammad_api/config.rbs new file mode 100644 index 00000000..5814f172 --- /dev/null +++ b/sig/zammad_api/config.rbs @@ -0,0 +1,69 @@ +module ZammadAPI + # Built with Data.define; the generated readers are declared explicitly. + # + # `middleware` is a block handed a Faraday::Connection, but it is declared + # untyped here: these signatures ship with the gem, while the Faraday + # declarations they would need live in sig/vendor, which does not. Naming + # Faraday here fails `rbs validate` for every consumer. + class Config < ::Data + DEFAULT_TIMEOUT: Integer + DEFAULT_OPEN_TIMEOUT: Integer + DEFAULT_RETRIES: Integer + DEFAULT_RETRY_INTERVAL: Float + REDACTION: String + DEFAULT_USER_AGENT: String + CREDENTIAL_OPTIONS: Hash[Symbol, Array[Symbol]] + + def self.new: (**untyped) -> instance + def self.merge_options: (Hash[Symbol, untyped] options, Hash[Symbol, untyped] overrides) -> Hash[Symbol, untyped] + + attr_reader url: String + attr_reader user: String? + attr_reader password: String? + attr_reader http_token: String? + attr_reader oauth2_token: String? + attr_reader user_agent: String + attr_reader timeout: Numeric + attr_reader open_timeout: Numeric + attr_reader retries: Integer + attr_reader retry_interval: Numeric + attr_reader ssl_verify: bool + attr_reader proxy: String? + attr_reader adapter: Symbol? + attr_reader middleware: untyped + attr_reader logger: Logger + + def initialize: ( + url: untyped, + ?user: String?, + ?password: String?, + ?http_token: String?, + ?oauth2_token: String?, + ?user_agent: String?, + ?timeout: untyped, + ?open_timeout: untyped, + ?retries: untyped, + ?retry_interval: untyped, + ?ssl_verify: bool, + ?proxy: String?, + ?adapter: (Symbol | String)?, + ?middleware: untyped, + ?logger: Logger? + ) -> void + + def authentication_scheme: () -> Symbol + def with: (**untyped) -> Config + def inspect: () -> String + def to_s: () -> String + def pretty_print: (untyped printer) -> void + def to_h: () -> Hash[Symbol, untyped] + + private + + def render: (Symbol, untyped) -> String + def normalize_url: (untyped) -> String + def validate_credentials!: () -> void + def present: (untyped) -> untyped + def stripped: (untyped) -> String? + end +end diff --git a/sig/zammad_api/deep_copy.rbs b/sig/zammad_api/deep_copy.rbs new file mode 100644 index 00000000..6e5d4cd3 --- /dev/null +++ b/sig/zammad_api/deep_copy.rbs @@ -0,0 +1,7 @@ +module ZammadAPI + module DeepCopy + def self?.frozen_copy: (untyped value) -> untyped + def self?.writable_copy: (untyped value) -> untyped + def self?.symbolize: (untyped key) -> untyped + end +end diff --git a/sig/zammad_api/errors.rbs b/sig/zammad_api/errors.rbs new file mode 100644 index 00000000..77b725f7 --- /dev/null +++ b/sig/zammad_api/errors.rbs @@ -0,0 +1,61 @@ +module ZammadAPI + class Error < StandardError + end + + class ConfigurationError < Error + end + + class UnknownResourceError < Error + end + + class TransportError < Error + end + + class ConnectionError < TransportError + end + + class TimeoutError < TransportError + end + + class ParseError < Error + end + + class PaginationError < Error + end + + class ResponseError < Error + STATUS_ERRORS: Hash[Integer, singleton(ResponseError)] + + attr_reader response: Response? + + def self.build: (Response response, String request) -> ResponseError + + def initialize: (String message, ?response: Response?) -> void + def status: () -> Integer? + def body: () -> untyped + def headers: () -> Hash[String, String] + def server_message: () -> String? + end + + class ClientError < ResponseError + end + + class ServerError < ResponseError + end + + class AuthenticationError < ClientError + end + + class AuthorizationError < ClientError + end + + class NotFoundError < ClientError + end + + class ValidationError < ClientError + end + + class RateLimitError < ClientError + def retry_after: () -> Integer? + end +end diff --git a/sig/zammad_api/resource_proxy.rbs b/sig/zammad_api/resource_proxy.rbs new file mode 100644 index 00000000..665a19f5 --- /dev/null +++ b/sig/zammad_api/resource_proxy.rbs @@ -0,0 +1,41 @@ +module ZammadAPI + # Generic over the resource it is the entry point for: `client.tickets` is a + # ResourceProxy[Resources::Ticket], so `find` answers with a Ticket and a + # block over it is handed one. + class ResourceProxy[R < Resources::Base] + include Enumerable[R] + + attr_reader resource_class: untyped + + @transport: Transport + + def initialize: (Transport, untyped resource_class) -> void + def new: (?hash[untyped, untyped] attributes) -> R + def create: (?hash[untyped, untyped] attributes) -> R + def find: (Integer | String id) -> R + def find_by: (**untyped) -> R? + def find_by!: (**untyped) -> R + def exists?: (Integer | String id) -> bool + def destroy: (Integer | String id) -> true + def all: () -> Collection[R] + def order: (*(Symbol | String) attributes, **(Symbol | String) directions) -> Collection[R] + + def each: () { (R) -> void } -> Collection[R] + | () -> Enumerator[R, Collection[R]] + def find_each: (?batch_size: Integer?) { (R) -> void } -> Collection[R] + | (?batch_size: Integer?) -> Enumerator[R, Collection[R]] + def in_batches: (?of: Integer?) { (Array[R]) -> void } -> Collection[R] + | (?of: Integer?) -> Enumerator[Array[R], Collection[R]] + def page: (Integer number, ?per_page: Integer?) -> Collection[R] + def pluck: (*(Symbol | String) keys) -> Array[untyped] + def empty?: () -> bool + def first: () -> R? + | (Integer count) -> Array[R] + def search: (String term, **untyped filters) -> Collection[R] + def inspect: () -> String + + private + + def find_by_id: (Hash[Symbol, untyped] params) -> R? + end +end diff --git a/sig/zammad_api/resources/base.rbs b/sig/zammad_api/resources/base.rbs new file mode 100644 index 00000000..04804ae1 --- /dev/null +++ b/sig/zammad_api/resources/base.rbs @@ -0,0 +1,66 @@ +module ZammadAPI + module Resources + class Base + include AttributeAccess + + DEFAULT_MAX_PER_PAGE: Integer + + attr_reader error: ValidationError? + + # What Zammad stamps every record with. These four are columns of every + # table, and the two names beside them are what `expand` adds: the login + # of each user. A record that was built with `new` and not saved yet + # carries none of them, and reading one then raises NoMethodError - the + # types here, and on every resource, describe a record Zammad served. + attr_reader created_by_id: Integer + attr_reader updated_by_id: Integer + attr_reader created_at: String + attr_reader updated_at: String + attr_reader created_by: String + attr_reader updated_by: String + + @new_record: bool + @destroyed: bool + @error: ValidationError? + @baseline: Hash[Symbol, untyped] + + def self.path: (String) -> void + def self.searchable: (bool) -> void + def self.max_per_page: (Integer) -> void + def self.sortable: (bool) -> void + def self.resource_path: () -> String + def self.searchable?: () -> bool + def self.page_limit: () -> Integer + def self.sortable?: () -> bool + def self.member_path: ((Integer | String) id) -> String + def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> Base + + def initialize: (Transport, ?hash[untyped, untyped]? attributes) -> void + def new_record?: () -> bool + def persisted?: () -> bool + def destroyed?: () -> bool + def changes: () -> Hash[Symbol, Array[untyped]] + def changed?: () -> bool + def assign_attributes: (hash[untyped, untyped] attributes) -> self + def save: () -> bool + def save!: () -> true + def update: (hash[untyped, untyped] attributes) -> bool + def update!: (hash[untyped, untyped] attributes) -> true + def reload: () -> self + def destroy: () -> true + def inspect: () -> String + + private + + attr_reader transport: Transport + + def mark_persisted!: () -> void + def load_response!: (Response response) -> void + def raise_if_new!: (String operation) -> void + def writable_attributes?: () -> bool + def write_attribute: (Symbol, untyped) -> untyped + def member_path: () -> String + def require_id!: () -> Integer + end + end +end diff --git a/sig/zammad_api/resources/resources.rbs b/sig/zammad_api/resources/resources.rbs new file mode 100644 index 00000000..8177e45c --- /dev/null +++ b/sig/zammad_api/resources/resources.rbs @@ -0,0 +1,201 @@ +module ZammadAPI + # The attributes declared on each resource are the long-standing columns + # of its table, typed the way their JSON arrives - a timestamp is a String, + # and `preferences` is a Hash with Symbol keys. + # + # They are declarations only. A record answers them through + # method_missing, from whatever the response carried, so nothing here makes + # an attribute exist: these say what a typed caller may rely on. + # + # What is left out, on purpose: + # + # - Attributes an administrator added. Reach one with `record[:name]`, or + # declare it in your own signatures by reopening the class: + # + # class ZammadAPI::Resources::Ticket + # attr_accessor escalation_reason: String? + # end + # + # - Columns that newer Zammad versions added, which an older instance does + # not serve. + # + # - The name `expand` adds for an association that may be empty, such as + # `organization` on a ticket or a user. Zammad leaves the key out rather + # than sending null, so the reader would raise rather than answer nil. + # `record[:organization]` is nil in that case, and `organization_id` is + # always there. + module Resources + class Group < Base + attr_accessor name: String + attr_accessor signature_id: Integer? + attr_accessor email_address_id: Integer? + attr_accessor assignment_timeout: Integer? + attr_accessor follow_up_possible: String + attr_accessor follow_up_assignment: bool + attr_accessor active: bool + attr_accessor note: String? + end + + class Organization < Base + attr_accessor name: String + attr_accessor shared: bool + attr_accessor domain: String? + attr_accessor domain_assignment: bool + attr_accessor active: bool + attr_accessor note: String? + end + + class TicketPriority < Base + attr_accessor name: String + attr_accessor default_create: bool + attr_accessor ui_icon: String? + attr_accessor ui_color: String? + attr_accessor active: bool + attr_accessor note: String? + end + + class TicketState < Base + attr_accessor name: String + attr_accessor state_type_id: Integer + attr_accessor next_state_id: Integer? + attr_accessor ignore_escalation: bool + attr_accessor default_create: bool + attr_accessor default_follow_up: bool + attr_accessor active: bool + attr_accessor note: String? + end + + class User < Base + # Narrowed from Base so Client#me returns the concrete user type. + def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> User + + attr_accessor login: String + attr_accessor firstname: String? + attr_accessor lastname: String? + attr_accessor email: String? + attr_accessor organization_id: Integer? + attr_accessor image: String? + attr_accessor image_source: String? + attr_accessor web: String? + attr_accessor phone: String? + attr_accessor fax: String? + attr_accessor mobile: String? + attr_accessor department: String? + attr_accessor street: String? + attr_accessor zip: String? + attr_accessor city: String? + attr_accessor country: String? + attr_accessor address: String? + attr_accessor vip: bool + attr_accessor verified: bool + attr_accessor active: bool + attr_accessor note: String? + attr_accessor out_of_office: bool + attr_accessor out_of_office_start_at: String? + attr_accessor out_of_office_end_at: String? + attr_accessor out_of_office_replacement_id: Integer? + attr_accessor preferences: Hash[Symbol, untyped]? + + # Set by Zammad as the user signs in, so there is nothing to write. + attr_reader last_login: String? + attr_reader login_failed: Integer + attr_reader source: String? + + # Zammad takes a password and never serves one. + attr_writer password: String + end + + class Ticket < Base + attr_accessor title: String + attr_accessor group_id: Integer + attr_accessor state_id: Integer + attr_accessor priority_id: Integer + attr_accessor owner_id: Integer + attr_accessor customer_id: Integer + attr_accessor organization_id: Integer? + attr_accessor note: String? + attr_accessor pending_time: String? + attr_accessor type: String? + attr_accessor preferences: Hash[Symbol, untyped]? + + # The name `expand` puts beside each of the ids above that cannot be + # empty. Writing one is how a ticket is moved by name: + # `ticket.update(state: 'closed', group: 'Support')`. + attr_accessor group: String + attr_accessor state: String + attr_accessor priority: String + attr_accessor owner: String + attr_accessor customer: String + + # Kept by Zammad as the ticket moves, so there is nothing to write. + attr_reader number: String + attr_reader article_count: Integer? + attr_reader create_article_type_id: Integer? + attr_reader create_article_sender_id: Integer? + attr_reader first_response_at: String? + attr_reader first_response_escalation_at: String? + attr_reader first_response_in_min: Integer? + attr_reader first_response_diff_in_min: Integer? + attr_reader close_at: String? + attr_reader close_escalation_at: String? + attr_reader close_in_min: Integer? + attr_reader close_diff_in_min: Integer? + attr_reader update_escalation_at: String? + attr_reader update_in_min: Integer? + attr_reader update_diff_in_min: Integer? + attr_reader escalation_at: String? + attr_reader last_contact_at: String? + attr_reader last_contact_agent_at: String? + attr_reader last_contact_customer_at: String? + attr_reader last_owner_update_at: String? + + def articles: () -> Array[TicketArticle] + def add_article: (?hash[untyped, untyped] attributes) -> TicketArticle + end + + class TicketArticle < Base + # Narrowed from Base so callers get the concrete article type. + def self.from_response: (Transport, Hash[untyped, untyped] attributes) -> TicketArticle + + attr_accessor ticket_id: Integer + attr_accessor type_id: Integer + attr_accessor sender_id: Integer + attr_accessor from: String? + attr_accessor to: String? + attr_accessor cc: String? + attr_accessor subject: String? + attr_accessor reply_to: String? + attr_accessor in_reply_to: String? + attr_accessor content_type: String + attr_accessor body: String + attr_accessor internal: bool + attr_accessor preferences: Hash[Symbol, untyped]? + + # The name `expand` puts beside type_id and sender_id, which is also + # how an article is given either: `add_article(type: 'note')`. + attr_accessor type: String + attr_accessor sender: String + + attr_reader message_id: String? + attr_reader message_id_md5: String? + attr_reader origin_by_id: Integer? + + def attachments: () -> Array[TicketArticleAttachment] + end + + class TicketArticleAttachment + include AttributeAccess + + @transport: Transport + + # What Zammad lists for each attachment of an article. + attr_reader filename: String + attr_reader size: String + attr_reader preferences: Hash[Symbol, untyped] + + def initialize: (Transport, ?Hash[untyped, untyped]? attributes) -> void + def download: () -> String + def inspect: () -> String + end + end +end diff --git a/sig/zammad_api/response.rbs b/sig/zammad_api/response.rbs new file mode 100644 index 00000000..577b63e4 --- /dev/null +++ b/sig/zammad_api/response.rbs @@ -0,0 +1,16 @@ +module ZammadAPI + # Built with Data.define; the generated readers are declared explicitly. + class Response < ::Data + attr_reader status: Integer + attr_reader headers: Hash[String, String] + attr_reader body: untyped + attr_reader raw_body: String + + def self.new: (status: Integer, headers: Hash[String, String], body: untyped, raw_body: String) -> instance + + def self.decode_body: (String?, String) -> untyped + + def success?: () -> bool + def decoded: (Symbol shape) -> untyped + end +end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs new file mode 100644 index 00000000..c90003d8 --- /dev/null +++ b/sig/zammad_api/transport.rbs @@ -0,0 +1,47 @@ +module ZammadAPI + # The Faraday connection and responses are untyped here rather than named: + # these signatures ship with the gem and the Faraday declarations they would + # need live in sig/vendor, which does not. See sig/zammad_api/config.rbs. + class Transport + def get: (String path, **untyped options) -> Response + def post: (String path, **untyped options) -> Response + def put: (String path, **untyped options) -> Response + def delete: (String path, **untyped options) -> Response + + RETRIABLE_METHODS: Array[Symbol] + RETRIABLE_STATUSES: Array[Integer] + RETRIABLE_EXCEPTIONS: Array[untyped] + SENSITIVE_KEY_PATTERN: Regexp + # private_constant in the source; RBS has no way to say so. + ABSOLUTE_URL: Regexp + + attr_reader config: Config + attr_reader on_behalf_of: String? + + @connection: untyped + + def self.escape_path_segment: (untyped) -> String + def self.relative_path: (untyped) -> String + def self.redact_path: (untyped path) -> String + def self.redact: (untyped value) -> untyped + + def initialize: (Config, ?on_behalf_of: String?) -> void + def with_on_behalf_of: (String? identifier) -> Transport + def with_config: (Config) -> Transport + def inspect: () -> String + + def request: (Symbol method, String path, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + + private + + def perform: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[untyped, untyped]?) -> untyped + def build_connection: () -> untyped + def retry_options: () -> Hash[Symbol, untyped] + def apply_authentication: (untyped) -> void + def decode: (untyped) -> Response + def log_request: (String, Hash[Symbol, untyped]?, untyped, Hash[untyped, untyped]?) -> void + def log_response: (String, Response, Float) -> void + def loggable_body: (untyped body) -> String + def logger: () -> Logger + end +end diff --git a/spec/typed/sig/usage.rbs b/spec/typed/sig/usage.rbs new file mode 100644 index 00000000..6e72c22a --- /dev/null +++ b/spec/typed/sig/usage.rbs @@ -0,0 +1,32 @@ +# The signatures a typed project writes for its own code. Not published with +# the gem: see spec/typed/usage.rb. +module TypedUsage + class Role < ZammadAPI::Resources::Base + attr_accessor name: String + end + + def self.title: (ZammadAPI::Client) -> String + def self.misspelled_reader: (ZammadAPI::Client) -> untyped + def self.logins: (ZammadAPI::Client) -> Array[String] + def self.block_parameter: (ZammadAPI::Client) -> untyped + def self.first_group: (ZammadAPI::Client) -> ZammadAPI::Resources::Group? + def self.first_tickets: (ZammadAPI::Client) -> Array[ZammadAPI::Resources::Ticket] + def self.found: (ZammadAPI::Client) -> ZammadAPI::Resources::Organization? + def self.newest_open: (ZammadAPI::Client) -> String? + def self.batches: (ZammadAPI::Client) -> Array[Integer] + def self.customer_email: (ZammadAPI::Client) -> String? + def self.article_bodies: (ZammadAPI::Client) -> Array[String] + def self.written: (ZammadAPI::Client) -> bool + def self.custom_attribute: (ZammadAPI::Client) -> [untyped, String?] + def self.role_names: (ZammadAPI::Client) -> Array[String] + def self.unsaved: (ZammadAPI::Client) -> String +end + +# An attribute an administrator added, declared by the project that uses it. +module ZammadAPI + module Resources + class Ticket + attr_accessor escalation_reason: String? + end + end +end diff --git a/spec/typed/usage.rb b/spec/typed/usage.rb new file mode 100644 index 00000000..ffb941aa --- /dev/null +++ b/spec/typed/usage.rb @@ -0,0 +1,74 @@ +# frozen_string_literal: true + +# Never run. `rake steep` checks this file against the signatures the gem +# publishes, the way a typed project that uses the gem is checked, so that the +# types a caller gets are pinned by something other than the signatures saying +# so. +# +# A line that ends in `steep:ignore` is one that has to be a type error. Steep +# reports an ignore comment that silences nothing, so each of them fails the +# check on the day its line stops being an error. That is how "a record is +# typed" is asserted here: against an untyped record a misspelled reader is no +# error at all, and the comment beside it would be the redundant one. +module TypedUsage + # A resource of the caller's own, reached through Client#resource. + class Role < ZammadAPI::Resources::Base + path 'api/v1/roles' + end + + def self.title(client) = client.tickets.find(1).title + + def self.misspelled_reader(client) + client.tickets.find(1).titel # steep:ignore NoMethod + end + + def self.logins(client) = client.users.map(&:login) + + def self.block_parameter(client) + client.users.each do |user| + user.loginn.upcase # steep:ignore NoMethod + end + end + + def self.first_group(client) = client.groups.first + + def self.first_tickets(client) = client.tickets.first(5) + + def self.found(client) = client.organizations.find_by(name: 'Zammad') + + def self.newest_open(client) + client.tickets.search('state.name:open').order(created_at: :desc).first&.number + end + + def self.batches(client) + sizes = [] #: Array[Integer] + client.tickets.in_batches(of: 50) { |tickets| sizes << tickets.sum { it.article_count || 0 } } + sizes + end + + def self.customer_email(client) = client.users.find(client.tickets.find(1).customer_id).email + + def self.article_bodies(client) = client.tickets.find(1).articles.map(&:body) + + def self.written(client) + ticket = client.tickets.find(1) + ticket.title = 'Printer on fire' + ticket.title = 1 # steep:ignore ArgumentTypeMismatch + ticket.number = '1' # steep:ignore NoMethod + ticket.save + end + + # An attribute an administrator added is read by name, or declared by the + # project that knows about it - see usage.rbs. + def self.custom_attribute(client) + ticket = client.tickets.find(1) + [ticket[:anything_at_all], ticket.escalation_reason] + end + + def self.role_names(client) + roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] + roles.map(&:name) + end + + def self.unsaved(client) = client.ticket_states.new(name: 'waiting').name +end From 5136f9c4fe9934d97880ba34808f30ceb8fe147e Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 1 Dec 2026 18:38:22 +0200 Subject: [PATCH 3/5] CI: test against three Zammads and publish by tag CI runs RuboCop, Steep and the unit specs on Ruby 3.4 and 4.0: on pull requests, on pushes, and weekly, to catch what a new Ruby or a new Zammad breaks. A further job boots a Zammad from source, waits for it to answer and runs the integration specs against it. It is a matrix over three: the stable-7.0 branch, stable and develop. A run started by hand with a zammad_ref tests that one ref in their place. The image the job runs in ships the Ruby of the develop branch, and a release pins an older one, so the job builds the Ruby that Zammad's .ruby-version names before it installs Zammad's gems. The specs run on the image's own Ruby either way. A release is published by pushing a v* tag, through RubyGems trusted publishing, so no API key is stored in the repository. Before it publishes, the workflow checks the tag against ZammadAPI::VERSION and the changelog, and runs the checks again. Dependabot groups its updates, so a week's bumps arrive as one pull request for the actions and one each for the runtime and the development gems. --- .github/dependabot.yml | 11 +++ .github/workflows/ci.yml | 163 +++++++++++++++++++++++++++++----- .github/workflows/release.yml | 44 +++++++++ 3 files changed, 196 insertions(+), 22 deletions(-) create mode 100644 .github/workflows/release.yml diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 710ebe83..84471df6 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,18 @@ updates: directory: "/" schedule: interval: "weekly" + groups: + actions: + patterns: ["*"] - package-ecosystem: "bundler" directory: "/" schedule: interval: "weekly" + groups: + # Lint and type tooling churns often and never affects the shipped gem. + development: + dependency-type: "development" + patterns: ["*"] + runtime: + dependency-type: "production" + patterns: ["*"] diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 144eff7a..57271a21 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,57 +1,176 @@ name: CI + on: push: branches: [master] pull_request: schedule: - # Run every on Friday to ensure everything works as expected. - - cron: '0 6 * * 5' + # Weekly, to catch breakage from new Ruby or Zammad releases. + - cron: '0 6 * * 5' + workflow_dispatch: + inputs: + zammad_ref: + description: 'One Zammad branch or tag to run the integration specs against, in place of the usual three (not a commit SHA)' + default: '' + type: string + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + jobs: lint: + name: RuboCop runs-on: ubuntu-latest - container: - image: zammad/zammad-ci:latest steps: - uses: actions/checkout@v7 - - name: Run lint actions - shell: bash - run: | - source /etc/profile.d/rvm.sh # ensure RVM is loaded - bundle update --bundler - bundle install -j $(nproc) - bundle exec rubocop - test: + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + - run: bundle exec rubocop --format github + + types: + name: Steep runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + - run: bundle exec steep check + # sig/vendor is always on the load path here but never in the gem, so + # the published set is checked on its own as well. + - run: bundle exec rake rbs_published + + unit: + name: Unit specs (Ruby ${{ matrix.ruby }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # Stable releases only, from required_ruby_version up to the current + # stable line. There is no 3.5: that line became 4.0. + ruby: ['3.4', '4.0'] + env: + # The unit specs do not need the type-checking toolchain, and skipping it + # keeps this job fast. The `types` job installs it separately. + BUNDLE_WITHOUT: development + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: ${{ matrix.ruby }} + bundler-cache: true + - name: Run unit specs + run: bundle exec rake spec:unit + env: + COVERAGE: 'true' + + integration: + name: Integration specs (Zammad ${{ matrix.zammad }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + # The oldest release line the gem is tested against, the current + # release, and what the next one is being built from. + zammad: ${{ fromJSON(inputs.zammad_ref && format('["{0}"]', inputs.zammad_ref) || '["stable-7.0", "stable", "develop"]') }} + # Booting Zammad costs far more runner time than the unit suite, so there + # is no point paying for it when the unit specs are already failing. + needs: unit + # A full Zammad boot takes many minutes; without a cap a hung boot would + # occupy a runner until the six hour default expires. + timeout-minutes: 45 container: image: zammad/zammad-ci:latest services: postgresql: - image: postgres:17 + image: postgres:18 env: POSTGRES_USER: zammad POSTGRES_PASSWORD: zammad redis: image: redis:7 + env: + ZAMMAD_REF: ${{ matrix.zammad }} + TEST_USER: admin@example.com + TEST_PASSWORD: test steps: - uses: actions/checkout@v7 - - name: Set up Zammad + + - name: Boot Zammad shell: bash run: | - git clone --depth 1 https://github.com/zammad/zammad.git + # No `set -u`: /etc/profile.d/rvm.sh reads unset variables and aborts + # under nounset. + set -eo pipefail + git clone --depth 1 --branch "$ZAMMAD_REF" https://github.com/zammad/zammad.git cd zammad - source /etc/profile.d/rvm.sh # ensure RVM is loaded + source /etc/profile.d/rvm.sh + # The image ships the Ruby of Zammad's develop branch. A release + # names an older one, which is built here; installing the one that + # is there already does nothing. The specs themselves run on the + # image's Ruby, in the steps below. + zammad_ruby="$(cat .ruby-version)" + # Where rvm unpacks a Ruby to build it, which the image leaves out. + mkdir -p "$rvm_path/src" + if ! rvm install "$zammad_ruby" || ! rvm use "$zammad_ruby"; then + echo "::error::could not provide Ruby $zammad_ruby for Zammad $ZAMMAD_REF" + exit 1 + fi bundle config set --local frozen 'true' bundle config set --local path 'vendor' - bundle install -j $(nproc) + bundle install -j "$(nproc)" bundle exec ruby .gitlab/configure_environment.rb source .gitlab/environment.env RAILS_ENV=test bundle exec rake db:create cp contrib/auto_wizard_test.json auto_wizard.json bundle exec rake zammad:ci:test:start - - name: Run Ruby API integration tests + echo "TEST_URL=http://localhost:3000/" >> "$GITHUB_ENV" + + - name: Wait for Zammad to answer + shell: bash + run: | + probe="${TEST_URL%/}/api/v1/getting_started" + for attempt in $(seq 1 60); do + if curl -sSf --max-time 5 "$probe" >/dev/null 2>&1; then + echo "Zammad answered at $TEST_URL after ${attempt} attempt(s)" + exit 0 + fi + sleep 5 + done + echo "::error::Zammad never answered at $probe" + exit 1 + + - name: Install the gem's dependencies + shell: bash + run: | + source /etc/profile.d/rvm.sh + bundle install -j "$(nproc)" + + - name: Run the integration specs + shell: bash + run: | + source /etc/profile.d/rvm.sh + bundle exec rake spec:integration + + - name: Collect Zammad logs on failure + if: failure() shell: bash run: | - source /etc/profile.d/rvm.sh # ensure RVM is loaded - bundle update --bundler - bundle install -j $(nproc) - bundle exec rspec + echo '--- zammad/log ---' + tail -n 200 zammad/log/*.log 2>/dev/null || echo 'no logs found' + + - name: Upload Zammad logs + if: failure() + uses: actions/upload-artifact@v7 + with: + name: zammad-logs-${{ matrix.zammad }} + path: zammad/log/ + if-no-files-found: ignore + retention-days: 7 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..1c6d6cbc --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,44 @@ +name: Release + +# Publishes to RubyGems via trusted publishing (OIDC), so no API key is +# stored in this repository. Configure the trusted publisher once at +# https://rubygems.org/gems/zammad_api/trusted_publishers +on: + push: + tags: ['v*'] + +permissions: + contents: read + +jobs: + release: + name: Build and publish + runs-on: ubuntu-latest + environment: rubygems + permissions: + contents: write # `rake release`, which the release action runs, pushes the tag + id-token: write # request the OIDC token for trusted publishing + steps: + - uses: actions/checkout@v7 + - uses: ruby/setup-ruby@v1 + with: + ruby-version: '4.0' + bundler-cache: true + # The tag is what triggers this workflow, and nothing downstream reads + # it: the gem is built from the gemspec, so a tag that disagrees with + # ZammadAPI::VERSION would publish a gem under a version nobody tagged. + - name: Check the tag against the gem version and the changelog + run: | + tagged="${GITHUB_REF_NAME#v}" + declared="$(ruby -Ilib -rzammad_api/version -e 'print ZammadAPI::VERSION')" + if [ "$tagged" != "$declared" ]; then + echo "::error::tag ${GITHUB_REF_NAME} does not match ZammadAPI::VERSION ($declared)" + exit 1 + fi + if ! grep -q "^## \[${declared}\]" CHANGELOG.md; then + echo "::error::CHANGELOG.md has no '## [${declared}]' heading" + exit 1 + fi + - name: Verify the release candidate + run: bundle exec rake + - uses: rubygems/release-gem@v1 From de54ad9932aa362f27ac4cd58eae6d54338ea904 Mon Sep 17 00:00:00 2001 From: Mantas Date: Tue, 1 Dec 2026 18:38:25 +0200 Subject: [PATCH 4/5] Docs: document 2.0 and the way up from 1.x The README is rewritten around the 2.0 API: creating a client, the resources, records, collections, acting on behalf of a user, errors, timeouts and retries, logging, the endpoints the gem does not model, and the type signatures. It says which Zammad the gem is tested against: 7.0, the current stable release and the develop branch. UPGRADING.md lists every call that changed. It starts with the changes that do not announce themselves, where 1.x code keeps running and does something different, and ends with how to stay on 1.x, whose code lives on the 1-stable branch. The changelog entry for 2.0.0.alpha1 carries the same changes as a list. ROADMAP.md sets what 1.x and 2.0 model beside the PHP client. CONTRIBUTING.md names the rake tasks and says how to run the integration specs against a disposable Zammad. The generated reference carries UPGRADING and the changelog and leaves the private API out, and LICENSE.md links to the licence texts by URL so that the links work from there too. --- .yardopts | 11 + CHANGELOG.md | 214 +++++++++++ CONTRIBUTING.md | 43 +++ LICENSE.md | 4 +- README.md | 922 ++++++++++++++++++++++++++++++++++-------------- ROADMAP.md | 28 ++ UPGRADING.md | 158 +++++++++ 7 files changed, 1119 insertions(+), 261 deletions(-) create mode 100644 .yardopts create mode 100644 CONTRIBUTING.md create mode 100644 ROADMAP.md create mode 100644 UPGRADING.md diff --git a/.yardopts b/.yardopts new file mode 100644 index 00000000..c10e67a1 --- /dev/null +++ b/.yardopts @@ -0,0 +1,11 @@ +--markup markdown +--readme README.md +--output-dir doc +--no-private +--query '@api.text != "private"' +--protected +lib/**/*.rb +- +UPGRADING.md +CHANGELOG.md +LICENSE.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 422138f6..642d2d56 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,207 @@ +# Changelog + +## [2.0.0.alpha1] - 2026-11-17 + +The first prerelease of 2.0, a breaking release that modernises the whole gem. See +[UPGRADING.md][upgrading] for the complete before/after guide. + +Everything below is what changed since 1.4.0. It is published as an alpha so that it can +still change: names, defaults and behaviour may differ in 2.0.0. A prerelease has to be +asked for, with `gem install zammad_api --pre` or `gem 'zammad_api', '~> 2.0.0.alpha'`. + +### Breaking + +- Ruby 3.4 or later is required. +- `Client.new` takes keyword arguments: `Client.new(**config)`. A positional Hash or an + unknown option raises `ArgumentError`. +- `logger:` takes a `Logger`, or anything that responds to `debug`, rather than `true`. +- The resource readers are plural: `client.tickets`, `client.users`, `client.groups`, + `client.organizations`, `client.ticket_articles`, `client.ticket_priorities` and + `client.ticket_states`. The singular names raise `NoMethodError`. +- The readers are a fixed list; 1.x resolved any `client.` to a class under + `ZammadAPI::Resources`. For another endpoint, use `client.resource(YourClass)`. +- `client.on_behalf_of = 'login'` and `client.perform_on_behalf_of` are + `client.on_behalf_of('login')`, which returns a new client and takes a block. A blank + identifier raises `ArgumentError`. +- A configuration with more than one kind of credentials raises `ConfigurationError`. + 1.x sent the first and ignored the rest. +- A collection walks every page. `each` used to stop after the first: 100 records for + `all`, 10 for `search`. +- A collection fetches as many records per request as the endpoint serves (1000 on most + index endpoints, 100 on tickets, 200 on a search) rather than a fixed 100. `page(n)` + without `per_page:` is a page of that size. +- `all` and `search` take no paging or filter keywords: `all(per_page: 50)` is + `find_each(batch_size: 50)` or `page(1, per_page: 50)`, `search(query: 'zammad')` is + `search('zammad')`, and `search(query: 'z', page: 2, per_page: 50)` is + `search('z').page(2, per_page: 50)`. `all(active: true)` never filtered; use `search` or + `detect`. +- `page(number, per_page)` with a block is `page(number, per_page: size)`, which returns a + new collection. `page_next`, `page_prev` and `Collection#[]` were removed. +- `Collection#find` with an id raises `ArgumentError`: it is `Enumerable#find`. Look a + record up with `client.tickets.find(1)`. +- `search` raises `ZammadAPI::Error` on `ticket_states`, `ticket_priorities` and + `ticket_articles`, which Zammad has no search endpoint for. +- `record.save` returns `false` on a validation failure and leaves it in `record.error`. + `save!` raises, and so does `create`. Every other failure raises from both. +- `record.destroy` and `record.reload` raise for a record that was never saved. `destroy` + marks the record `destroyed?`, and `persisted?` is false for it. +- `record.id = ...` raises `ZammadAPI::Error`. +- `record.attributes` and `record.changes` are frozen, and `record.to_h` is a deep copy. + Assign through a writer to stage a change. +- `record.attributes = {...}` is no longer a writer: it stages an attribute called + `attributes`. Use `assign_attributes` or `update`. +- A reader for an attribute the record does not carry raises `NoMethodError` instead of + answering `nil`. Use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` where an attribute may + be absent. +- `record.new_instance` is `new_record?` and `persisted?`, and the instance-level `url` is + the class-level `resource_path`. +- `ticket.article(…)` is `ticket.add_article(…)`. +- `ZammadAPI::Error` descends from `StandardError` instead of `RuntimeError`. +- `ZammadAPI::ResourceNotFoundError` is `ZammadAPI::UnknownResourceError`, raised by + `client.resource(:name)` for a name that is no resource. A 404 is + `ZammadAPI::NotFoundError`. +- No Faraday exception leaves a request: an unreachable host raises + `ZammadAPI::ConnectionError` and a timeout `ZammadAPI::TimeoutError`. +- `ResponseError#response` is a `ZammadAPI::Response`, not a Faraday object, and `#body` is + the decoded payload. +- An error message names the request that failed: + `GET api/v1/tickets/1 failed: Couldn't find Ticket with 'id'="1"`. + `ResponseError#operation` and `#resource_class` were removed. +- `ZammadAPI::ListBase`, `ListAll` and `ListSearch` are `ZammadAPI::Collection`, and + `ZammadAPI::Dispatcher` is `ZammadAPI::ResourceProxy`. `ZammadAPI::Log` and + `ZammadAPI::JsonHelper` were removed. + +### Added + +- `client.get`, `client.post`, `client.put` and `client.delete` reach any endpoint of the + Zammad API, with `query:`, `body:` and `headers:`. They return a `ZammadAPI::Response` + and keep authentication, timeouts, retries, credential redaction, JSON decoding and the + error classes. A path is relative to the instance URL, and one that opens with a scheme + raises `ArgumentError`, so the credentials stay with the configured instance. +- Request and connection timeouts (`timeout`, `open_timeout`), on by default at 60 and + 10 seconds. 1.x waited as long as the server took, so a call that used to hang now + raises `TimeoutError`, or `ConnectionError` when the connection is not opened in time. +- Automatic retry with exponential backoff for a `GET` on connection failures, timeouts + and the statuses 429, 500, 502, 503 and 504. A `Retry-After` within `timeout` is + honoured, and a longer one ends the retries. A write is never retried: a repeated ticket + update carrying an `article` adds that article, and sends its e-mail, twice. +- A specific error class per status: `AuthenticationError` (401), `AuthorizationError` + (403), `NotFoundError` (404), `ValidationError` (422) and `RateLimitError` (429, with + `#retry_after`). Network failures raise `ConnectionError` or `TimeoutError`. +- `Collection#order`, `#page`, `#in_batches`, `#find_each`, `#count`, `#pluck` and + `#empty?`, plus `client.x.order(...)` as a shorthand for `all.order(...)`. +- `order` sorts on the server: `order(:name)`, `order(name: :desc)`, + `order(:active, name: :desc)`, read the way ActiveRecord reads them, and a second + `order` sorts within the first. `/api/v1/tickets` and `/api/v1/users` hardcode id order, + so `order` on those raises `ArgumentError`; a search sorts for every resource that can be + searched. +- `search(term, **filters)` passes its keywords on to the search endpoint, for what it + narrows by besides the term: `condition:` and `ids:`, and `role_ids:`, `group_ids:` and + `permissions:` on users. A blank term raises `ArgumentError`; `'*'` asks for every record. +- A resource proxy is `Enumerable` over `all`, so `client.tickets.each`, + `client.tickets.first(5)`, `client.tickets.map`, `#find_each`, `#in_batches`, `#page`, + `#pluck` and `#count` all work without naming `all`. `client.x.find(id)` keeps + its own meaning rather than becoming `Enumerable#find`; `detect` is the block form. +- `Collection#count` costs a single request on a search endpoint, which Zammad can count + without returning the records. Elsewhere it walks. +- `Collection#first` sizes its own request: `all.first` is one request for one record and + `all.first(5)` one request for five. `empty?` asks for one record the same way. +- A walk of an index ends at the first page shorter than the size it asked for, and a + search walk at the first empty page, since Zammad can serve a short page with more hits + behind it. +- `client..find_by(**params)` and `#find_by!`, which look a record up by + attribute value, and `client..exists?(id)`. `find_by` answers with the first + record that carries all the values, or `nil`: by its id where `id:` is given, through a + search for the longest String value where the resource has a search endpoint, and by + walking the index everywhere else. +- The page size is clamped to what an endpoint serves (100 for `/api/v1/tickets`, 200 for + a search, 1000 for the other index endpoints). Asking for more used to end iteration + after the first page, because Zammad capped the response and the short page read as the + end of the list. +- `ZammadAPI::PaginationError`, raised when an endpoint answers a page with the records of + the page before it, instead of paging forever. +- `Base#reload`, `#persisted?`, `#destroyed?`, `#[]`, `#[]=`, `#fetch`, `#key?`, `#to_h` and + a readable `#inspect` that blanks attributes naming a credential. +- `record.update(attributes)`, `record.update!(attributes)` and + `record.assign_attributes(attributes)`. Attributes can be a Hash or anything with + `to_hash`, such as permitted `ActionController::Parameters`. +- `ssl_verify`, `proxy`, `user_agent`, `retries` and `retry_interval` client options. + The default `User-Agent` is now `zammad_api-ruby/` rather than + `Zammad API Ruby`. +- `adapter` and `middleware` client options, the seam into the Faraday stack, for a + persistent-connection adapter or instrumentation. An adapter set inside the + `middleware:` callable takes the place of `adapter:`. A Faraday error while building the + connection surfaces as `ConfigurationError`. +- RBS signatures in `sig/`, verified by Steep in CI. +- `respond_to?` answers correctly for attribute readers and resource methods. +- Records implement `deconstruct_keys`, so they can be used with `case/in` pattern + matching. `Config` and `Response` are `Data` objects and match as well. +- `Client#with(**options)` derives a new client with changed options. The options are + re-validated, any `on_behalf_of` scope is carried over, and naming credentials replaces + the ones the client has. +- `Client.from_env` builds a client from `ZAMMAD_URL`, `ZAMMAD_TOKEN`, + `ZAMMAD_OAUTH2_TOKEN`, `ZAMMAD_USER` and `ZAMMAD_PASSWORD`, with + passed-in options winning. A blank variable counts as unset. +- `Client#me`, the user the credentials authenticate as, and `Client#version`, the version + of the Zammad instance. +- `Response#decoded(:object | :array)` checks the shape of a response body in one place, + so an unexpected payload raises `ParseError`. +- Records compare as the Zammad records they came from: two records of the same kind with + the same id are equal, and `#hash` agrees, so `uniq`, `Set`, `include?` and records as + Hash keys all work. A record with no id stays equal only to itself. +- `record.to_json` and `record.as_json` render a record's attributes. `to_json` previously + fell through to `Object#to_json`, which serialized a record as the string + `"#"`. +- `client.resource(SomeClass)` takes a subclass of `ZammadAPI::Resources::Base` and answers + with a proxy for it, so an endpoint this gem does not model gets records, pagination, + `find_by`, change tracking and `save` from a class that declares its `path`. `searchable`, + `max_per_page` and `sortable` say what else is true of the endpoint. +- Typed records. `ResourceProxy` and `Collection` are generic over the resource they hold, + so `client.tickets` is a `ResourceProxy[Resources::Ticket]` and `find`, `first`, + `find_by`, the block of `each` and a search all answer with a `Ticket`. Each resource + declares the long-standing attributes of its kind, so `ticket.title` is a + `String` and `ticket.titel` is a type error. `spec/typed/usage.rb` is checked by + `rake steep` the way a caller's code is. + +### Fixed + +- Credentials no longer reach the debug log or `inspect`: 1.x logged `user:password` when a + client was built and wrote payloads out as they stood. Keys, query parameters and headers + that name a credential are redacted, and a path is logged without its query string. +- An exception inside the block of `perform_on_behalf_of` no longer leaves the `From` + header set on every later request; the block form of `on_behalf_of` scopes a client of + its own. +- A Zammad served from a sub-path (`https://example.com/zammad/`) works; 1.x sent every + request to the root of the host. +- Query parameters are encoded by Faraday; 1.x sent a list or a Hash, such as a search + `condition`, as its Ruby `inspect`. +- A Hash inside an Array attribute has Symbol keys like every other; 1.x left it the + String keys Zammad sent. +- A response body that is not JSON is no longer read as an empty Hash: a 2xx where a + record was expected raises `ParseError`. +- A name that is no resource raises rather than resolving to a class that is not a + resource, as `client.base` resolved to `Resources::Base`. +- Record ids are percent-encoded wherever they go into a path, attachment downloads and + article lists included. +- `save` on a record with nothing staged sends no request; 1.x sent an empty `PUT`, which + bumped `updated_at` and `updated_by`. +- `record[:x] = 1` stages the attribute it names; 1.x took it for an attribute called `[]`. +- `add_article` on a ticket that has not been saved raises `ZammadAPI::Error`, where 1.x's + `article` posted it with `ticket_id: null`. +- A `url` carrying `user:password@` raises `ConfigurationError`, where 1.x sent those in + place of a configured token, and so does one without a host, such as `http://:3000/`, + which 1.x sent to localhost. +- A subclass of a resource inherits its API path; in 1.x `class MyTicket < Ticket; end` + had none. + +### Changed + +- `client..destroy(id)` deletes directly instead of fetching the record first. +- `client.` returns the same proxy each time rather than allocating one per call. + The proxies are built with the client, so a client stays immutable once built and safe to + share between threads. +- A String request body is sent as it is rather than encoded as a JSON string. + ## [1.4.0] - 2026-08-25 - Follow up - c3af2a9 - Fixes #29 - [JSON::ParserError on gateway timeout when proxy responds with HTML](https://github.com/zammad/zammad-api-client-ruby/issues/29) - Dependencies updated @@ -19,3 +223,13 @@ ## [1.0.7] - 2022-04-14 - Updated package dependencies and tests. + +[upgrading]: https://github.com/zammad/zammad-api-client-ruby/blob/master/UPGRADING.md +[2.0.0.alpha1]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.4.0...v2.0.0.alpha1 +[1.4.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.3.1...v1.4.0 +[1.3.1]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.3.0...v1.3.1 +[1.3.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.2.0...v1.3.0 +[1.2.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.1.0...v1.2.0 +[1.1.0]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.0.8...v1.1.0 +[1.0.8]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.0.7...v1.0.8 +[1.0.7]: https://github.com/zammad/zammad-api-client-ruby/compare/v1.0.6...v1.0.7 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 00000000..24fb8a36 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,43 @@ +# Contributing + +```sh +bin/setup # bundle install, plus the overcommit git hooks +bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures +``` + +| Task | What it does | +| ------------------------ | ----------------------------------------------------- | +| `rake spec:unit` | Unit specs; stubbed, no Zammad needed | +| `rake spec:integration` | Integration specs against a live Zammad | +| `rake spec` | Both; needs `TEST_URL`, like the integration specs | +| `rake rubocop` | Style checks | +| `rake steep` | Type-check `lib/` against `sig/`, and `spec/typed/` the way a caller is checked | +| `rake rbs_published` | Validate the signatures the gem ships, without `sig/vendor/` | + +Set `COVERAGE=true` to produce a coverage report in `coverage/`. + +## Testing against a live Zammad + +The integration specs need a reachable Zammad instance and **will create and delete +records**, so they run only where `TEST_URL` names one, and there is no default: point it +at something disposable. Without it, `rspec` runs the unit specs and says the integration +specs were left out, `rspec spec/integration` fails for having nothing to run, and +`rake spec:integration` and `rake spec` stop before running anything. + +```sh +export TEST_URL=https://zammad.example/ # a disposable Zammad, never one you keep data in +export TEST_USER=admin@example.com # an administrator +export TEST_PASSWORD=test + +bundle exec rake spec:integration +``` + +`spec/integration/zammad_api_spec.rb` is the whole suite. Each example creates the records +it needs under a name of its own and destroys them afterwards, and none asserts on what +else the instance holds, so it can run against the same Zammad any number of times, in +any order. A freshly booted Zammad is set up by its auto wizard on the first request. + +CI runs it against three Zammads booted from source: the `stable-7.0` branch, `stable` and +`develop`. For each, the `integration` job clones Zammad, starts it, waits for it to +answer, then runs the integration specs. Trigger it by hand from the Actions tab +(`workflow_dispatch`) to test against another Zammad branch or tag. diff --git a/LICENSE.md b/LICENSE.md index 17882e4f..1b3f0375 100644 --- a/LICENSE.md +++ b/LICENSE.md @@ -2,5 +2,5 @@ This program is free software; you can redistribute it and/or modify it under the terms of either: -1. the [GNU Affero General Public License](LICENSE.AGPL.txt) as published by the Free Software Foundation version 3 -2. the [MIT License](LICENSE.MIT.txt) as published by the Open Source Initiative \ No newline at end of file +1. the [GNU Affero General Public License](https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.AGPL.txt) as published by the Free Software Foundation version 3 +2. the [MIT License](https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.MIT.txt) as published by the Open Source Initiative \ No newline at end of file diff --git a/README.md b/README.md index 211469b6..31ec7802 100644 --- a/README.md +++ b/README.md @@ -1,390 +1,794 @@ -# Zammad API Client (Ruby) [![Gem Version](https://badge.fury.io/rb/zammad_api.svg)](https://badge.fury.io/rb/zammad_api) +# Zammad API Client (Ruby) -## API version support -This client supports Zammad API version 1.0. +[![Gem Version](https://badge.fury.io/rb/zammad_api.svg)](https://badge.fury.io/rb/zammad_api) +[![CI](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/zammad/zammad-api-client-ruby/actions/workflows/ci.yml) + +> [!IMPORTANT] +> `2.0.0.alpha1` is the first prerelease of a breaking 2.0. Names and defaults can still +> change: [open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) with +> anything that reads wrong, is missing, or makes upgrading hard. Rough notes are welcome. +> On 1.x? See [UPGRADING.md][upgrading], which also says how to stay on 1.x. + +Ruby client for the Zammad API v1.0. + +- Tickets, articles, attachments, users, organizations, groups, ticket states and + priorities as records you `find`, `create`, `update` and `destroy`. +- Collections that paginate themselves: `each`, `first`, `search`, `find_each`. +- Timeouts, and retries for `GET`, on by default, and one error class per kind of failure. +- Any other endpoint through a resource you declare or a raw request. ## Installation -Add this line to your application's Gemfile: +Requires Ruby 3.4 or later. It is tested against Zammad 7.0, the current stable release +and the `develop` branch: CI runs the integration specs against all three on every change +and once a week. Older Zammad releases are not part of that run. + +2.0 is a prerelease, and a prerelease has to be asked for: ```ruby -gem 'zammad_api' +gem 'zammad_api', '~> 2.0.0.alpha' ``` -And then execute: +Or: - $ bundle +```sh +gem install zammad_api --pre +``` -Or install it yourself as: +## Quick start - $ gem install zammad_api +```ruby +require 'zammad_api' -## Available objects +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'your-access-token' +) + +client.tickets.first(5).each { |ticket| puts ticket.title } + +ticket = client.tickets.create( + title: 'Cannot log in', + group: 'Users', + customer: 'nicole.braun@zammad.org', + article: {subject: 'Cannot log in', body: 'My password stopped working.', type: 'note'} +) -* user -* organization -* group -* ticket -* ticket_article -* ticket_state -* ticket_priority +ticket.add_article(body: 'Reset link sent.', type: 'note') +ticket.update(state: 'closed') -## Usage +client.tickets.search('state.name:open').each { |open_ticket| puts open_ticket.number } -### Create instance +begin + client.tickets.find(123_456) +rescue ZammadAPI::NotFoundError => e + warn e.server_message +end +``` -#### Username/email and password +The sections below cover [creating a client](#creating-a-client), +[records](#working-with-records), [collections](#collections) and +[error handling](#error-handling). + +## Creating a client + +### Authentication ```ruby client = ZammadAPI::Client.new( - url: 'http://localhost:3000/', - user: 'user', - password: 'some_pass' + url: 'https://zammad.example.com/', + http_token: 'your-access-token' ) ``` -#### Access token +Or pass `oauth2_token:`, or `user:` and `password:`. Pass one kind of credentials: more +than one raises `ZammadAPI::ConfigurationError`. + +### From the environment + +`from_env` reads `ZAMMAD_URL` and one of `ZAMMAD_TOKEN`, `ZAMMAD_OAUTH2_TOKEN`, or +`ZAMMAD_USER` with `ZAMMAD_PASSWORD`. Options passed to it override the environment: ```ruby -client = ZammadAPI::Client.new( - url: 'http://localhost:3000/', - http_token: '12345678901234567890', -) +client = ZammadAPI::Client.from_env +client = ZammadAPI::Client.from_env(timeout: 300) ``` -#### OAuth2 +### Options + +| Option | Default | Description | +| ---------------- | ------------------ | ------------------------------------------------------------------ | +| `url` | *required* | Base URL. A sub-path such as `https://example.com/zammad/` works; credentials in it are refused. | +| `http_token` | `nil` | Zammad access token. | +| `oauth2_token` | `nil` | OAuth2 bearer token. | +| `user` | `nil` | Login for basic authentication. | +| `password` | `nil` | Password for basic authentication. | +| `timeout` | `60` | Seconds to wait for a response. | +| `open_timeout` | `10` | Seconds to wait for the connection. | +| `retries` | `2` | Retry attempts for a `GET` that failed transiently. `0` disables retrying. | +| `retry_interval` | `0.5` | Seconds before the first retry; doubles on each attempt. | +| `ssl_verify` | `true` | Set to `false` only against a server with a self-signed certificate. | +| `proxy` | `nil` | Proxy URL. | +| `user_agent` | `zammad_api-ruby/` | Value of the `User-Agent` header. | +| `logger` | discards output | Any `Logger`; see [Logging](#logging). | +| `adapter` | Faraday's default | Name of a Faraday adapter; see [Adapter and middleware](#adapter-and-middleware). | +| `middleware` | `nil` | Callable that is handed the Faraday connection while it is built. | + +Credentials are never logged, and `client.config` redacts them when printed. + +### Changing options + +A client is immutable. `with` returns a new one with some options changed, carrying over +any `on_behalf_of` scope: ```ruby -client = ZammadAPI::Client.new( - url: 'http://localhost:3000/', - oauth2_token: '12345678901234567890', -) +bulk = client.with(timeout: 300, retries: 5) +bulk.tickets.each { |ticket| archive(ticket) } +``` + +Naming credentials replaces the ones the client has, whichever kind they were. Because +clients are immutable, one client and anything derived from it can be shared between +threads. + +### Checking the connection + +```ruby +client.me.email # => "agent@example.com", the account the credentials belong to +client.version # => "6.4.0", the Zammad instance's version, for an administrator ``` -## Resource management +`client.me` works for any account, so use it to check that the client can reach Zammad and +authenticate. Zammad serves `client.version` to administrators only: with an agent's or a +customer's credentials it raises `ZammadAPI::AuthorizationError`. `ZammadAPI::VERSION` is +the version of this gem. + +## Resources + +`groups`, `organizations`, `tickets`, `ticket_articles`, `ticket_priorities`, +`ticket_states`, `users` + +`client.resource_names` returns the current list. Anything else is reachable by declaring +a resource or with raw requests; see +[Endpoints this gem does not model](#endpoints-this-gem-does-not-model). -Individual resources can be created, modified, saved, and destroyed. +## Working with records -### Create object +### Create -With new and save: ```ruby -group = client.group.new( - name: 'Support', - note: 'Some note', -); -group.save +user = client.users.new(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org') +user.save -group.id # id of record -group.name # 'Support' +user.id # => 42 +user.email # => "nicole.braun@zammad.org" ``` -With create: -```ruby -group = client.group.create( - name: 'Support', - note: 'Some note', -); +Or in one call: -group.id # id of record -group.name # 'Support' +```ruby +user = client.users.create(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org') ``` -### Fetch object +Attributes are a Hash, or anything that converts to one with `to_hash`. In a Rails +controller that is the permitted parameters: ```ruby -group = client.group.find(123) -puts group.inspect +client.users.create(params.require(:user).permit(:login, :email, :password)) ``` -### Update object + +### Fetch ```ruby -group = client.group.find(123) -group.name = 'Support 2' -group.save +user = client.users.find(42) # raises NotFoundError if there is none + +client.users.find_by(email: 'someone@example.com') # => the record, or nil +client.users.find_by!(email: 'nobody@example.com') # raises NotFoundError +client.users.exists?(42) # => true ``` -### Destroy object +`find_by` returns the first record carrying all of the given values, or `nil`. It searches +where the resource has a search endpoint and one of the values is a String; otherwise it +reads the index page by page, which can take many requests on a large instance. What a +search matches is up to Zammad's search index, so where a miss must be certain, read the +index yourself: `client.tickets.detect { it[:state] == 'open' }`. + +### Reading attributes ```ruby -group = client.group.find(123) -group.destroy +user.email # => "nicole.braun@zammad.org" +user[:email] # the same, and nil when the attribute is absent +user.fetch(:email) # raises KeyError when the attribute is absent +user.key?(:email) # => true +user.to_h # every attribute, as a Hash you may modify ``` -## Collection management +A reader for an attribute the record does not carry raises `NoMethodError`, so a typo does +not read as `nil`. Use `record[:name]` or `fetch(:name, nil)` where an attribute may be +absent: custom attributes, or records the authenticated user may only partly see. -A list of individual resources. +`attributes` and `changes` are frozen. Assign through a writer (`user.email = '...'`) to +stage a change. -### All +### Update ```ruby -groups = client.group.all +user = client.users.find(42) +user.firstname = 'Nicola' -group1 = groups[0] -group1.note = 'Some note' -group1.save +user.changed? # => true +user.changes # => {firstname: ["Nicole", "Nicola"]} -groups.each {|group| - p "group: #{group.name}" -} +user.save # sends only the changed attributes ``` -### Search +`save` with no changes sends no request and returns `true`. Assigning the value an +attribute already has is not a change. + +Or in one call: + ```ruby -groups = client.group.search(query: 'some name') +user.update(firstname: 'Nicola', note: 'Renamed') # assigns, then saves +user.assign_attributes(firstname: 'Nicola') # assigns without saving +``` + +### Saving and validation failures -group1 = groups[0] -group1.note = 'Some note' -group1.save +`save` returns whether the record was stored, and leaves a rejection in `error`: -groups.each {|group| - p "group: #{group.name}" -} +```ruby +organization = client.organizations.new(name: '') + +if organization.save + puts organization.id +else + warn organization.error.server_message # => "Name can't be blank" +end ``` -### All with pagination (beta) +Only a validation failure (HTTP 422) is reported this way. Every other failure raises. + +`save!` and `update!` raise on every failure, including validation: ```ruby -groups = client.group.all +organization.save! # raises ZammadAPI::ValidationError +organization.update!(name: '') # the same, in one call +``` + +`create` raises on a validation failure, like `save!`. Use `new` and `save` to branch +instead. -groups.page(1,3) {|group| - p "group: #{group.name}" +### Reload and destroy - group.note = 'Some new note, inclued in page 1 with 3 per page' - group.save -} +```ruby +user.reload # re-reads from Zammad, discarding unsaved changes +user.destroy # => true -groups.page(2,3) {|group| - p "group: #{group.name}" +user.destroyed? # => true +user.persisted? # => false - group.note = 'Some new note, inclued in page 2 with 3 per page' - group.save -} +client.users.destroy(42) # delete by id, without fetching first ``` -### Search with pagination (beta) +### Associations + +Zammad expands an association into a name beside the id, so those reads cost nothing: + ```ruby -groups = client.group.search(query: 'some name') +ticket = client.tickets.find(1) -groups.page(1,3) {|group| - p "group: #{group.name}" +ticket.customer # => "customer@example.com" +ticket.state # => "open" +ticket.group # => "Users" +ticket.customer_id # => 7 +``` + +The whole record behind one of those is a `find` by its id, which costs a request: - group.note = 'Some new note, inclued in page 1 with 3 per page' - group.save -} +```ruby +client.users.find(ticket.customer_id).firstname # => "Nicole" +``` -groups.page(2,3) {|group| - p "group: #{group.name}" +A foreign key that may be empty, such as a user's `organization_id`, is `nil` then, and +`find` needs an id: - group.note = 'Some new note, inclued in page 2 with 3 per page' - group.save -} +```ruby +user.organization_id && client.organizations.find(user.organization_id) ``` -## Perform actions on behalf of another user +### Articles and attachments + +```ruby +ticket.articles # => [TicketArticle, ...] +ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle + +ticket.articles.each do |article| + article.attachments.each do |attachment| + File.binwrite(File.basename(attachment.filename), attachment.download) + end +end +``` -As described in the [Zammad API documentation](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users) it is possible to perfom actions on behalf other users. To use this feature you can set the attribute of the client accordingly: +`articles` is one request, and is fetched on each call. `download` returns the file +contents as a binary String. -> **Note:** This feature requires Zammad 5.0 or later, since the client sends the standard HTTP `From` header instead of the deprecated `X-On-Behalf-Of` header (see [zammad/zammad#3113](https://github.com/zammad/zammad/issues/3113)). +To send a file, give the article its `attachments`, each with its content encoded as +Base64: ```ruby -client.on_behalf_of = 'some_login' +ticket.add_article( + body: 'Invoice attached.', + type: 'note', + attachments: [{ + filename: 'invoice.pdf', + data: [File.binread('invoice.pdf')].pack('m0'), + 'mime-type': 'application/pdf' + }] +) ``` -All following actions with the client will be performed on behalf of the user with the `login` "some_login". +`pack('m0')` is what `Base64.strict_encode64` does, without the `base64` gem, which Ruby +no longer ships by default. The `article:` of `client.tickets.create` takes `attachments` +the same way. + +### Comparing and serializing -To reset this back to regular requests just set `nil`: +Two records of the same kind with the same id are equal, so `uniq`, `Set` and `include?` +work as expected: ```ruby -client.on_behalf_of = nil +client.tickets.find(1) == client.tickets.find(1) # => true ``` -It's possible to perform only a block of actions on behalf of another user via: +`to_json` renders the attributes, and `as_json` returns them as a Hash: ```ruby -client.perform_on_behalf_of('some_login') do - # ticket is created on behalf of the user with - # the login "some_login" - client.ticket.create( - ... - ) +client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" +``` + +### Pattern matching + +Records implement `deconstruct_keys`, so they work with `case/in`: + +```ruby +case client.tickets.find(1) +in {state: 'closed'} + nil +in {state: String => state, priority: '3 high'} + escalate(state) +in {group: 'Support'} + notify_support end +``` -# further actions are performed regularly. -``` - -## Examples - -Create a ticket: -```ruby -ticket = client.ticket.create( - title: 'a new ticket #1', - state: 'new', - group: 'Users', - priority: '2 normal', - customer: 'some_customer@example.com', - article: { - content_type: 'text/plain', # or text/html, if not given test/plain is used - body: 'some body', - # attachments can be optional, data needs to be base64 encoded - attachments: [ - 'filename' => 'some_file.txt', - 'data' => 'dGVzdCAxMjM=', - 'mime-type' => 'text/plain', - ], - }, -) +## Collections + +`all`, `search` and `order` return a `ZammadAPI::Collection`. It is `Enumerable`, makes no +request until you iterate, and fetches pages as needed. + +### Iterating + +```ruby +client.tickets.each { |ticket| puts ticket.title } + +# One request, for five records. +client.tickets.first(5) + +# Lazy chains stop fetching once they have enough. +client.tickets.lazy.select { |ticket| ticket.state == 'open' }.first(10) + +# One array of records per request, e.g. for a bulk import. +client.tickets.in_batches(of: 50) { |tickets| import(tickets) } + +# Record by record, 50 per request. +client.tickets.find_each(batch_size: 50) { |ticket| archive(ticket) } + +# Attribute values instead of records. +client.users.pluck(:email) # => ["a@example.com", ...] +client.tickets.pluck(:id, :title) # => [[1, "Help"], ...] +``` + +`client.tickets` and `client.tickets.all` are the same collection. Nothing is cached, so +iterating again fetches again. + +`client.tickets.find(1)` looks up by id. To find with a block, use `detect`. + +### Searching -ticket.id # id of record -ticket.number # uniq number of ticket -ticket.title # 'a new ticket #1' -ticket.group # 'Support' -ticket.created_at # '2022-01-01T12:42:01Z' -# ... +```ruby +client.tickets.search('state.name:open').each { |ticket| puts ticket.title } +client.organizations.search('zammad').first(10) ``` -List all new or open tickets: +Zammad's index endpoints do not filter; only the search endpoints do. That is why a +collection has no `where`. `users`, `organizations`, `tickets` and `groups` can be +searched. On the others `search` raises `ZammadAPI::Error`, so use `find_by` or `select`: + ```ruby -tickets = client.ticket.search(query: 'state.name:new OR state.name:open') +client.ticket_states.find_by(name: 'open') +client.ticket_priorities.select { it.active } +``` -ticket[0].id # id of record -ticket[0].number # uniq number of ticket -ticket[0].title # 'title of ticket' -ticket[0].group # 'Support' -ticket[0].created_at # '2022-01-01T12:42:01Z' +Keywords are passed on to the search endpoint as query parameters: `condition:` and `ids:` +on every search, and `role_ids:`, `group_ids:` and `permissions:` on users. Zammad ignores +a parameter it does not read. -tickets.each {|ticket| - p "ticket: #{ticket.number} - #{ticket.title}" -} +```ruby +client.users.search('smith', role_ids: [2]) +client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) ``` -Get all articles of a ticket: +A blank term raises `ArgumentError`. `search('*')` asks for every record. + +### Sorting + +`order` sorts on the server: + ```ruby -ticket = client.ticket.find(123) -articles = ticket.articles +client.groups.order(:name) # ascending +client.organizations.order(name: :desc) +client.groups.order(:active, name: :desc) # by active, then by name descending +``` -articles[0].id # id of record -articles[0].from # creator of article -articles[0].to # recipients of article -articles[0].subject # article subject -articles[0].body # text of message -articles[0].content_type # text/plain or text/html of .body -articles[0].type # 'note' -articles[0].sender # 'Customer' -articles[0].created_at # '2022-01-01T12:42:01Z' +`/api/v1/tickets` and `/api/v1/users` are always served in id order, so `order` on +`client.tickets` or `client.users` raises `ArgumentError`. Sort a search instead: -p "ticket: #{ticket.number} - #{ticket.title}" -articles.each {|article| - p "article: #{article.from} - #{article.subject}" -} +```ruby +client.tickets.search('state.name:open').order(created_at: :desc) ``` -Create an article for a ticket: +### Pages + +```ruby +client.tickets.page(2) # page 2 at the size the endpoint serves +client.tickets.page(2, per_page: 10) # records 11 to 20 +``` + +By default a request asks for the largest page the endpoint serves: 100 for tickets, 200 +for a search, 1000 elsewhere. Pass a smaller size with `find_each(batch_size:)`, +`in_batches(of:)` or `page(n, per_page:)`; a larger one is capped. + +Collections are immutable: `order` and `page` return a new collection. + +### Counting + +`count` on a search is one request. Every other collection is read page by page, because +an index endpoint reports no total: + ```ruby -ticket = client.ticket.find(123) +client.tickets.search('state.name:open').count # one request +client.tickets.count # one request per page +client.tickets.search('state.name:merged').empty? # one request, for one record +``` -article = ticket.article( - type: 'note', - subject: 'some subject 2', - body: 'some body 2', - # attachments can be optional, data needs to be base64 encoded - attachments: [ - 'filename' => 'some_file.txt', - 'data' => 'dGVzdCAxMjM=', - 'mime-type' => 'text/plain', - ], +## Acting on behalf of another user + +Zammad can perform +[actions on behalf of another user](https://docs.zammad.org/en/latest/api/intro.html#actions-on-behalf-of-other-users). +`on_behalf_of` returns a new client: + +```ruby +support = client.on_behalf_of('agent@example.com') +support.tickets.create(title: 'Help', group: 'Users', customer_id: 1) +``` + +Or scoped to a block: + +```ruby +client.on_behalf_of('agent@example.com') do |scoped| + scoped.tickets.find(1) +end +``` + +The identifier can be a login, an email address or a user id. A `nil` or blank identifier +raises `ArgumentError`. This sends the HTTP `From` header and requires Zammad 5.0 or later. + +## Error handling + +```ruby +begin + client.tickets.find(1) +rescue ZammadAPI::NotFoundError + nil +rescue ZammadAPI::RateLimitError => e + # The client already waited and retried, so this limit outlasted that. + reschedule(in: e.retry_after || 60) +rescue ZammadAPI::ResponseError => e + warn "#{e.status}: #{e.server_message}" + warn e.body.inspect +end +``` + +`save` and `update` return `false` on a 422 instead of raising; see +[Saving and validation failures](#saving-and-validation-failures). + +Every error descends from `ZammadAPI::Error`: + +```text +ZammadAPI::Error +├── ZammadAPI::ConfigurationError invalid client options +├── ZammadAPI::UnknownResourceError no such resource, e.g. client.resource(:unicorn) +├── ZammadAPI::ParseError unexpected response shape +├── ZammadAPI::PaginationError endpoint ignored the page parameter +├── ZammadAPI::TransportError +│ ├── ZammadAPI::ConnectionError unreachable host, TLS failure or open_timeout +│ └── ZammadAPI::TimeoutError exceeded timeout +└── ZammadAPI::ResponseError carries the HTTP response + ├── ZammadAPI::ClientError 4xx + │ ├── ZammadAPI::AuthenticationError 401 + │ ├── ZammadAPI::AuthorizationError 403 + │ ├── ZammadAPI::NotFoundError 404 + │ ├── ZammadAPI::ValidationError 422 + │ └── ZammadAPI::RateLimitError 429 + └── ZammadAPI::ServerError 5xx +``` + +`ResponseError` exposes `response` (a `ZammadAPI::Response`) and, as shortcuts, `status`, +`body`, `headers` and `server_message`. Its message names the request that failed: +`GET api/v1/tickets/1 failed: Couldn't find Ticket with 'id'="1"`. + +A `TransportError` is a request with no answer, which is not the same as one Zammad never +saw: a write that timed out may have been applied. + +### Timeouts and retries + +A `GET` is retried on connection failures, timeouts and the statuses 429, 500, 502, 503 +and 504, with exponential backoff. A write is never retried. Both are options: + +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + timeout: 10, + retries: 5 ) +``` + +A `Retry-After` header is honoured up to `timeout` seconds. A longer one is not waited +out: the request fails at once, and `RateLimitError#retry_after` carries the figure. + +A write that fails raises, because repeating it could create a second record or send an +e-mail twice. The calling code decides whether to send it again: + +```ruby +begin + ticket.update!(state: 'closed') +rescue ZammadAPI::TransportError, ZammadAPI::ServerError + ticket.reload # did it arrive? + retry if ticket.state != 'closed' +end +``` + +## Logging -article.id # id of record -article.from # creator of article -article.to # recipients of article -article.subject # article subject -article.body # text of message -article.content_type # text/plain or text/html of .body -article.type # 'note' -article.sender # 'Customer' -article.created_at # '2022-01-01T12:42:01Z' -article.attachments.each { |attachment| - attachment.filename # 'some_file.txt' - attachment.size # 1234 - attachment.preferences # { :"Mime-Type"=>"image/jpeg" } - attachment.download # content of attachment / extra REST call will be executed -} - -p "article: #{article.from} - #{article.subject}" -``` - -Create an article with html and inline images for a ticket: -```ruby -ticket = client.ticket.find(123) - -article = ticket.article( - type: 'note', - subject: 'some subject 2', - body: 'some body with an image Red dot', - content_type: 'text/html', # optional, default is text/plain +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + logger: Logger.new($stdout) ) +``` -article.id # id of record -article.from # creator of article -article.to # recipients of article -article.subject # article subject -article.body # text of message -article.content_type # text/plain or text/html of .body -article.type # 'note' -article.sender # 'Customer' -article.created_at # '2022-01-01T12:42:01Z' -article.attachments.each { |attachment| - attachment.filename # '122.146472496@www.znuny.com' - attachment.size # 1167 - attachment.preferences # { :'Mime-Type'=>'image/jpeg', :'Content-ID'=>'122.146472496@www.znuny.com', :'Content-Disposition'=>'inline'} } - attachment.download # content of attachment / extra REST call will be executed -} +Requests, response statuses and durations are logged at `debug` level. Anything that +responds to `debug` works in place of a `Logger`. Payload keys, query parameters and +headers that look like credentials (`password`, `token`, `secret`, `cookie`, ...) are +redacted, and a path is logged without its query string. + +## Endpoints this gem does not model + +### Declaring a resource + +For an endpoint that serves records like the modelled ones (an index, and a member under +its id), declare a class with a path. `client.resource` then works like `client.tickets`: + +```ruby +class Role < ZammadAPI::Resources::Base + path 'api/v1/roles' +end -p "article: #{article.from} - #{article.subject}" +roles = client.resource(Role) + +roles.each { |role| puts role.name } +roles.find(2).update(note: 'Reviewed') +roles.create(name: 'Auditor') +roles.find_by(name: 'Agent') ``` -## Testing +Declare where the endpoint differs from the defaults: + +| Declaration | Default | Says | +| ------------------ | ---------- | ------------------------------------------------------------- | +| `path '…'` | *required* | The index endpoint, relative to the instance URL. | +| `searchable true` | `false` | Zammad routes `/search`, so `search` works and `find_by` uses it. | +| `max_per_page 100` | `1000` | The largest page the index endpoint serves. | +| `sortable false` | `true` | The index endpoint is always served in the same order, so `order` refuses it. | + +A subclass of a modelled resource works too, and inherits what its parent declares: +`class MyTicket < ZammadAPI::Resources::Ticket`. + +For an endpoint that ignores `page` and returns everything at once, or one that is an +action, a report or a setting, use a raw request. + +### Raw requests + +`get`, `post`, `put` and `delete` reach any endpoint of the Zammad API, with the same +authentication, timeouts, retries and error classes: -### Setup an (empty Zammad) test env +```ruby +client.get('api/v1/roles').body +# => [{id: 1, name: "Admin", ...}, ...] + +client.post('api/v1/tags/add', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) +client.put('api/v1/roles/2', body: {note: 'Updated'}) +client.delete('api/v1/tags/remove', query: {object: 'Ticket', o_id: 1, item: 'urgent'}) +client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) ``` -git clone git@github.com:zammad/zammad.git -cd zammad -export RAILS_ENV="test" -export APP_RESTART_CMD="bundle exec rake zammad:ci:app:restart" -script/bootstrap.sh && echo '' > log/test.log -cp contrib/auto_wizard_test.json auto_wizard.json -bundle exec rake zammad:ci:test:start + +A `body:` is sent as JSON, and a String body is sent as it is. Each call returns a +`ZammadAPI::Response`: + +```ruby +response = client.get('api/v1/tickets') +response.status # => 200 +response.headers['content-type'] +response.body # decoded JSON, or the raw body for anything else +response.raw_body # the body as it arrived ``` -### Execute client tests +Paths are relative to the instance URL, and a leading slash is ignored. A path that opens +with a scheme, such as `https://other.example/collect`, raises `ArgumentError`, so the +client's credentials only go to the instance it was configured for. + +### Coverage -Run tests via `rake spec`. (Remember to export the vars above if you are running this in another shell.) +Modelled: tickets, ticket articles and their attachments, ticket states and priorities, +users, organizations and groups, the same set as 1.x. -## Publishing +Not modelled yet: roles; text modules; ticket tags, links, mentions, time accounting, +checklists, shared drafts, merge and history; the knowledge base; global search; CSV +imports. Declare a resource or use raw requests for those, and +[open an issue](https://github.com/zammad/zammad-api-client-ruby/issues/new) for the one +you need, so we know what to model first. -1. Update version in [version.rb](lib/zammad_api/version.rb). -2. Add release to [CHANGELOG.md](CHANGELOG.md) -3. Commit. -4. Test build. +The [features roadmap][roadmap] shows what is planned for 2.0, beside 1.x and the +PHP client. + +## Adapter and middleware + +The client is built on Faraday. `adapter:` picks the Faraday adapter, and `middleware:` +adds your own middleware, such as instrumentation or a cache: + +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + adapter: :net_http_persistent, + middleware: ->(connection) { connection.use(MyInstrumentation) } +) ``` -> rake build -zammad_api 1.0.7 built to pkg/zammad_api-1.0.7.gem. + +To pass arguments to an adapter, set it inside the callable: +`->(connection) { connection.adapter :net_http_persistent, pool_size: 5 }`. Do not add +`response :json` or `response :raise_error`; the client decodes JSON and maps errors +itself. + +Faraday's default adapter opens a connection per request. For anything that reads many +pages, downloads attachments in a loop or runs a worker pool, add +`faraday-net_http_persistent` to your Gemfile and pass `adapter: :net_http_persistent`. + +## Type signatures + +RBS signatures ship in `sig/` and are checked in CI with [Steep](https://github.com/soutaro/steep). +Add the gem to your own RBS collection to type-check calls into this client. Records are +typed, not only the client: + +```ruby +ticket = client.tickets.find(1) + +ticket.title # String +ticket.organization_id # Integer? +ticket.titel # a type error: no such attribute is declared ``` -5. Release + +Attributes an administrator added, columns only newer Zammad versions serve, and expanded +association names that can be absent (such as `organization`) are not declared. Read those +with `ticket[:name]`, or reopen the class in your own signatures: + +```rbs +class ZammadAPI::Resources::Ticket + attr_accessor escalation_reason: String? +end ``` -> rake release -zammad_api 1.0.7 built to pkg/zammad_api-1.0.7.gem. -Tag v1.0.7 has already been created. -Pushing gem to https://rubygems.org... -You have enabled multi-factor authentication. Please enter OTP code. -Code: ...... -Successfully registered gem: zammad_api (1.0.7) -Pushed zammad_api 1.0.7 to https://rubygems.org +A resource of your own needs an annotation: + +```ruby +roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] ``` -## Contributing +## Recipes + +### Resuming a long read + +Keep the page number yourself when a job has to survive being interrupted. Save it once a +page is handled, so a rerun repeats at most one page: + +```ruby +page = File.exist?('cursor') ? Integer(File.read('cursor')) : 1 + +loop do + tickets = client.tickets.page(page, per_page: 50).to_a + break if tickets.empty? + + import(tickets) + + page += 1 + File.write('cursor', page) +end +``` + +A page number is a position, so this suits a list that only grows: tickets are served in +id order, and new ones arrive at the end. + +`in_batches` without a block is an Enumerator, for pulling one page at a time as a +consumer is ready: `pages = client.tickets.in_batches(of: 50)`, then `pages.next`. + +### Sharing one client between threads + +A client is immutable, so one instance serves every thread, and an `on_behalf_of` scope in +one thread cannot leak into another. In Rails, build it once in an initializer: + +```ruby +# config/initializers/zammad.rb +ZAMMAD = ZammadAPI::Client.new( + url: Rails.application.credentials.zammad_url, + http_token: Rails.application.credentials.zammad_token, + logger: Rails.logger +) +``` + +A worker pool shares it the same way: + +```ruby +queue = Queue.new +client.tickets.first(40).each { queue << it.id } +queue.close + +workers = Array.new(4) do + Thread.new do + while (id = queue.pop) + sync(client.tickets.find(id)) + end + end +end + +workers.each(&:join) +``` + +## Development + +```sh +bin/setup # bundle install, plus the overcommit git hooks +bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures +``` + +Integration specs need a disposable Zammad named by `TEST_URL`; see +[CONTRIBUTING.md][contributing]. + +## Upgrading from 1.x + +Most code needs one rename: `client.ticket` is `client.tickets`. Nearly everything else +that changed raises at the call site. [UPGRADING.md][upgrading] lists every change, and +says how to stay on 1.x. + +## License + +Dual licensed under the [AGPL-3.0-only][agpl] or [MIT][mit] licenses. See +[LICENSE.md][license]. -Bug reports and pull requests are welcome on [GitHub](https://github.com/zammad/zammad-api-client-ruby). This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct. +[upgrading]: https://github.com/zammad/zammad-api-client-ruby/blob/master/UPGRADING.md +[contributing]: https://github.com/zammad/zammad-api-client-ruby/blob/master/CONTRIBUTING.md +[roadmap]: https://github.com/zammad/zammad-api-client-ruby/blob/master/ROADMAP.md +[agpl]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.AGPL.txt +[mit]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.MIT.txt +[license]: https://github.com/zammad/zammad-api-client-ruby/blob/master/LICENSE.md diff --git a/ROADMAP.md b/ROADMAP.md new file mode 100644 index 00000000..146e1fa7 --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,28 @@ +# Features roadmap + +What each Zammad API client models: this gem in its 1.x and 2.0 versions, and the +[PHP client](https://github.com/zammad/zammad-api-client-php). + +✅ available · 🚧 planned · ❌ not available + +| Resource | Ruby 1.x | Ruby 2.0 | PHP | +| ------------------------- | :------: | :------: | ---------------------------------------------------- | +| Tickets | ✅ | ✅ | ✅ | +| Ticket articles | ✅ | ✅ | ✅ per ticket only, no index | +| Article attachments | ✅ | ✅ | ✅ no class; `getAttachmentContent()` on the article | +| Ticket states | ✅ | ✅ | ✅ | +| Ticket priorities | ✅ | ✅ | ✅ | +| Users | ✅ | ✅ | ✅ | +| Organizations | ✅ | ✅ | ✅ | +| Groups | ✅ | ✅ | ✅ | +| Roles | ❌ | 🚧 | ✅ | +| Tags | ❌ | 🚧 | ✅ list, search, add, remove | +| Links | ❌ | 🚧 | ✅ ticket to ticket | +| Text modules | ❌ | 🚧 | ✅ | +| CSV import: users | ❌ | 🚧 | ✅ | +| CSV import: organizations | ❌ | 🚧 | ✅ | +| CSV import: text modules | ❌ | 🚧 | ✅ | + +Until a 🚧 row lands in Ruby 2.0, reach it by +[declaring a resource](README.md#declaring-a-resource) or with a +[raw request](README.md#raw-requests). diff --git a/UPGRADING.md b/UPGRADING.md new file mode 100644 index 00000000..f403b0dc --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,158 @@ +# Upgrading from 1.x + +Version 2.0 fixes long-standing behaviour that could not change without breaking +compatibility. Most calling code needs one rename: the resource names are plural, so +`client.ticket` is `client.tickets`. Almost everything else that needs an edit raises at +the call site. Start with the few changes that do not. + +If this is not the time to move, [1.x stays available](#staying-on-1x). + +## Silent changes + +- **`record.attributes = {...}`** was a writer in 1.x. It is now an ordinary attribute + assignment, so it stages a change named `attributes` and `save` sends it to Zammad: + + ```ruby + group.attributes = {name: 'Support'} + group.changes # => {attributes: [nil, {name: "Support"}]} + ``` + + Use `assign_attributes(name: 'Support')`, or `update` to assign and save. + +- **`record.save`** returns `false` when Zammad rejects the attributes, where 1.x raised. + Code that relied on the exception carries on after a rejected save: + + ```ruby + ticket.state = 'closed' + ticket.save # false on a 422 in 2.0; nothing raises, and the ticket is still open + ``` + + Check what `save` returns and read `record.error`, or call `save!`, which raises + `ZammadAPI::ValidationError` as `save` used to. `update` and `update!` are the same pair. + +- **`collection.each`** reads every page, where 1.x stopped after the first (100 records + for `all`, 10 for `search`). A loop that used to touch the first 100 tickets now touches + all of them. To keep the old limit, use `first(n)` or `page(1, per_page: n)`. + +- **A Hash inside an Array attribute** has Symbol keys, where 1.x left it the String keys + Zammad sent: only a Hash directly under another Hash was symbolized. Read by String key, + it answers `nil` and nothing raises: + + ```ruby + article.attributes[:attachments].first['filename'] # the name in 1.x, nil in 2.0 + article.attributes[:attachments].first[:filename] # the name in 2.0 + ``` + + Keys are Symbols at every depth now, so one spelling reads a value wherever it sits. + +- **`rescue Faraday::ConnectionFailed`** (and any other Faraday exception) no longer + matches. Transport failures are wrapped, so rescue `ZammadAPI::ConnectionError`, + `ZammadAPI::TimeoutError`, or `ZammadAPI::TransportError` for both. + +## The client + +| 1.x | 2.0 | Why | +| -------------------------------------- | ------------------------------------------------ | -------------------------------------------------------------------- | +| `Client.new(config_hash)` | `Client.new(**config_hash)` | Options are keyword arguments now, so a Hash has to be splatted | +| an unknown option was ignored | raises `ArgumentError: unknown keyword` | A typo'd option used to be dropped without a word | +| `logger: true` | `logger: Logger.new($stderr)` | The flag became an object. Anything that responds to `debug` works | +| `client.ticket`, `client.user`, … | `client.tickets`, `client.users`, … | A resource is every record of its kind. The singular names raise `NoMethodError` | +| `client.on_behalf_of = 'login'` | `client.on_behalf_of('login')` → new client | The setter mutated the client and leaked across threads | +| `client.perform_on_behalf_of('x') { }` | `client.on_behalf_of('x') { \|scoped\| ... }` | The old block form left the header set if the block raised | +| `ZammadAPI::Resources::Role < Base` reached by `client.role` | `client.resource(Role)`, for a `Role < ZammadAPI::Resources::Base` of your own | The named readers are a fixed list. [Raw requests][raw-requests] reach whatever is not a resource | + +## Collections + +| 1.x | 2.0 | Why | +| ---------------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------- | +| `collection.page(1, 3) { \|r\| ... }` | `collection.page(1, per_page: 3).each { ... }` | `page` now returns a collection instead of mutating and yielding | +| `collection.page_next` / `page_prev` | `collection.page(n)` or `in_batches` | Removed; they mutated shared state | +| `collection[3]` | `collection.page(4, per_page: 1).first` | An index that costs a request, and that ignored `page`, was a trap | +| `collection.find(1)` | `client.x.find(1)`, or `collection.detect { ... }` | `find` on a collection is `Enumerable#find`; an id raises `ArgumentError` | +| `client.x.all(per_page: 50)` | `client.x.all.page(1, per_page: 50)`, `find_each(batch_size: 50)` | `all` accepted the argument and discarded it; page size belongs to the call that reads | +| `client.x.all(active: true)` | `client.x.search(...)`, or `client.x.all.detect { ... }` | Zammad's index endpoints do not filter, so 1.x ignored the argument | +| `client.x.search(query: 'zammad')` | `client.x.search('zammad')` | The search term is the argument, not a keyword | +| `client.x.search(query: 'z', page: 2, per_page: 50)` | `client.x.search('z').page(2, per_page: 50)` | Search did honour those two; paging is the collection's job now | + +## Records + +| 1.x | 2.0 | Why | +| ----------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------- | +| `record.attributes[:x] = 1` | `record.x = 1`, or `record.to_h` for a copy | Writing through the reader staged no change, so `save` never sent it | +| `record.id = 5` | `client.x.find(5)` | The id addresses the record, so a staged one deleted or updated a different record than it reported. It raises `ZammadAPI::Error` now | +| `record.new_instance` | `record.new_record?` / `record.persisted?` | Internal flag is no longer public; the old name raises `NoMethodError` | +| `resource.url` (instance) | `Resource.resource_path` (class) | Clashed with an attribute named `url` | +| `record.unknown_attribute` → `nil` | raises `NoMethodError`; use `record[:x]`, `fetch(:x, nil)` or `key?(:x)` | A typo used to read as `nil` | +| `ticket.article(body: '…')` | `ticket.add_article(body: '…')` | Renamed; `ticket.article(...)` raises `NoMethodError` | + +## Errors + +| 1.x | 2.0 | Why | +| ------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------------- | +| `ZammadAPI::Error < RuntimeError` | `ZammadAPI::Error < StandardError` | `RuntimeError` is for `raise "string"` | +| `ZammadAPI::ResourceNotFoundError` | `ZammadAPI::UnknownResourceError`, from `client.resource(:name)`; `NoMethodError` from `client.name` | Renamed so it is not confused with a 404, now `NotFoundError`. A reader the client does not have is a missing method like any other | +| `ClientError` for every 4xx | `AuthenticationError`, `NotFoundError`, `ValidationError`, … | All still `ClientError`, so existing rescues keep working | +| `error.response` was a Faraday object | `ZammadAPI::Response` with `status`/`body`/`headers` | Faraday is no longer part of the public surface | +| `error.body` was a raw JSON string | decoded Hash, or the raw body for non-JSON | Saves every caller from parsing it again | +| `"Can't find object (ZammadAPI::Resources::Ticket): …"` | `"GET api/v1/tickets/1 failed: …"` | A message names the request that failed, so match on the error class or `status`, not on its text | +| `error.operation`, `error.resource_class` | removed; read the request from `error.message` | They existed to word the message | + +## Removed constants, and the Ruby version + +| 1.x | 2.0 | Why | +| ------------------------------------------------ | -------------------------- | ------------------------------------------------------------ | +| `ZammadAPI::ListBase` / `ListAll` / `ListSearch` | `ZammadAPI::Collection` | One class instead of three | +| `ZammadAPI::Dispatcher` | `ZammadAPI::ResourceProxy` | Renamed; `client.` hands you one | +| `ZammadAPI::Log`, `ZammadAPI::JsonHelper` | removed | Pass any `Logger` as `logger:`; decoding moved into the transport | +| Ruby >= 3.0 | Ruby >= 3.4 | 3.0 through 3.3 are end-of-life or nearly so | + +## New defaults + +A collection fetches as many records per request as the endpoint serves: 1000 on most +index endpoints (1.x: 100), 100 on tickets (unchanged) and 200 on a search (1.x: 10). +`page(n)` without `per_page:` is a page of that size, so pin it with +`page(n, per_page: 100)` if a persisted page number has to keep meaning what it did. + +A request times out after 60 seconds (10 to connect), where 1.x waited as long as the +server took. A call that used to hang raises `ZammadAPI::TimeoutError`, or +`ZammadAPI::ConnectionError` when the connection is not opened in time. A `GET` is retried +twice with exponential backoff on connection failures, timeouts and the transient +statuses; a `POST`, `PUT` or `DELETE` is never retried. Both are options: see +[Timeouts and retries][timeouts-and-retries]. The `User-Agent` is +`zammad_api-ruby/` rather than `Zammad API Ruby`. + +## What did not change + +`find`, `all`, `create` and `new` on a resource, `record.destroy`, attribute readers and +writers, `ticket.articles` and `attachment.download`. + +`record.save`, `record.changes` and `record.attributes` still exist and still mean what +they meant; the tables above only change how they behave at the edges. + +## Staying on 1.x + +1.x stays available for a project that is not ready for 2.0, or that runs on a Ruby older +than 3.4: 1.x needs Ruby 3.0 or later. + +Its code lives on the +[`1-stable`](https://github.com/zammad/zammad-api-client-ruby/tree/1-stable) branch, and +the [README there](https://github.com/zammad/zammad-api-client-ruby/blob/1-stable/README.md) +documents the 1.x API. To install it, keep the version below 2: + +```ruby +gem 'zammad_api', '~> 1.4' +``` + +Or: + +```sh +gem install zammad_api -v '~> 1.4' +``` + +1.x is in maintenance mode, and will stay there for the foreseeable future: it still gets +fixes, while new features go into 2.0 only. Report a 1.x problem in the same +[issue tracker](https://github.com/zammad/zammad-api-client-ruby/issues), naming the +version, and open a pull request for it against `1-stable`. + +[raw-requests]: https://github.com/zammad/zammad-api-client-ruby/blob/master/README.md#raw-requests +[timeouts-and-retries]: https://github.com/zammad/zammad-api-client-ruby/blob/master/README.md#timeouts-and-retries From 57032a9f2196dbacb538ee0ae460ab52d6cf3615 Mon Sep 17 00:00:00 2001 From: DerPixler Date: Thu, 26 Nov 2026 21:51:09 +0100 Subject: [PATCH 5/5] Update ROADMAP with requested features section Added a new section for requested features not yet planned, detailing user requests and their sources. [Mantas: "once work on it starts" reads "once it is planned", to match the legend] --- ROADMAP.md | 65 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/ROADMAP.md b/ROADMAP.md index 146e1fa7..080f5273 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -5,6 +5,8 @@ What each Zammad API client models: this gem in its 1.x and 2.0 versions, and th ✅ available · 🚧 planned · ❌ not available +## Resources + | Resource | Ruby 1.x | Ruby 2.0 | PHP | | ------------------------- | :------: | :------: | ---------------------------------------------------- | | Tickets | ✅ | ✅ | ✅ | @@ -26,3 +28,66 @@ What each Zammad API client models: this gem in its 1.x and 2.0 versions, and th Until a 🚧 row lands in Ruby 2.0, reach it by [declaring a resource](README.md#declaring-a-resource) or with a [raw request](README.md#raw-requests). + +## Behaviour + +| Behaviour | Ruby 1.x | Ruby 2.0 | PHP | +| ------------------------------------- | :------: | --------------------------- | ------------------------------------------------ | +| Auto-pagination | ❌ | ✅ | ✅ | +| Total count of a search | ❌ | ✅ | ✅ | +| Sorted search | ❌ | ✅ not on tickets and users | ✅ as plain query parameters | +| Search by condition | ❌ | ✅ | ❌ | +| Acting on behalf of a user | ✅ | ✅ | ✅ by wrapping the request handler | +| Custom attributes | ✅ | ✅ | ✅ tickets, users, organizations and groups only | +| Typed errors | ✅ | ✅ | ✅ | +| Timeouts | ❌ | ✅ | ✅ | +| Retry when rate limited | ❌ | ✅ reads only | ✅ | +| Retry on server and connection errors | ❌ | ✅ reads only | ❌ | +| Attachment download as a stream | ❌ | ❌ | ❌ | +| Attachment upload helper | ❌ | ❌ | ❌ Base64 in the article | +| Test doubles for applications | ❌ | ❌ | ❌ | +| Framework integration | - | - | ✅ Laravel, Symfony | + +## Requested, not planned yet + +What users ask for beyond the tables above, most requested first. Neither client +offers these today; all are reachable with a raw request. A row moves into a +table above once it is planned. + +| Request | Where it was asked | +| ----------------------------------------- | ------------------------------------------------------------- | +| Attachments: upload, stream, delete | [PHP #4][php-4], community [10604][c-10604], [17478][c-17478], [13390][c-13390] | +| Listing beyond the 10,000 search limit | community [10644][c-10644], [16162][c-16162], [zammad #768][z-768] | +| Time accounting | community [10244][c-10244], [7958][c-7958], [17492][c-17492] | +| Knowledge base | [PHP #29][php-29], community [3510][c-3510], [12168][c-12168] | +| Tested Zammad versions per client release | [zammad #6561][z-6561], community [17422][c-17422] | +| Find or create a user by exact email | [PHP #9][php-9], [Ruby #6][ruby-6] | +| Ticket merge | community [4710][c-4710] | +| Ticket history | community [10205][c-10205] | +| Mentions, checklists, shared drafts | community [15937][c-15937], [20651][c-20651] | +| Webhook signature verification | community [9011][c-9011] | + +Missing something? Open an issue so we know what to model first. + +[php-4]: https://github.com/zammad/zammad-api-client-php/issues/4 +[php-9]: https://github.com/zammad/zammad-api-client-php/issues/9 +[php-29]: https://github.com/zammad/zammad-api-client-php/issues/29 +[ruby-6]: https://github.com/zammad/zammad-api-client-ruby/issues/6 +[z-768]: https://github.com/zammad/zammad/issues/768 +[z-6561]: https://github.com/zammad/zammad/issues/6561 +[c-3510]: https://community.zammad.org/t/3510 +[c-4710]: https://community.zammad.org/t/4710 +[c-7958]: https://community.zammad.org/t/7958 +[c-9011]: https://community.zammad.org/t/9011 +[c-10205]: https://community.zammad.org/t/10205 +[c-10244]: https://community.zammad.org/t/10244 +[c-10604]: https://community.zammad.org/t/10604 +[c-10644]: https://community.zammad.org/t/10644 +[c-12168]: https://community.zammad.org/t/12168 +[c-13390]: https://community.zammad.org/t/13390 +[c-15937]: https://community.zammad.org/t/15937 +[c-16162]: https://community.zammad.org/t/16162 +[c-17422]: https://community.zammad.org/t/17422 +[c-17478]: https://community.zammad.org/t/17478 +[c-17492]: https://community.zammad.org/t/17492 +[c-20651]: https://community.zammad.org/t/20651