diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 710ebe8..84471df 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 144eff7..538a049 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,57 +1,182 @@ 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: 'Zammad branch or tag to run the integration specs against (not a commit SHA)' + default: 'develop' + 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. + # + # 'head' is absent: it could not install the bundle when it was last + # tried, under a lockfile that named Bundler 2.6.9. The lockfile names + # Bundler 4 now, and head has not been retried since. + 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 (live Zammad) runs-on: ubuntu-latest + # 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: ${{ inputs.zammad_ref || 'develop' }} + TEST_USER: admin@example.com + TEST_PASSWORD: test steps: - uses: actions/checkout@v7 - - name: Set up Zammad + + - name: Report the toolchain shell: bash run: | - git clone --depth 1 https://github.com/zammad/zammad.git + source /etc/profile.d/rvm.sh + # The gem requires Ruby >= 3.4; fail here with a clear message rather + # than inside a confusing bundler resolution error. + ruby -v + ruby -e 'abort "zammad-ci image ships Ruby #{RUBY_VERSION}, this gem needs >= 3.4" if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("3.4")' + + - name: Boot Zammad + shell: bash + run: | + # 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 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 + # Each workflow step runs in its own shell, so Zammad's generated + # environment has to be promoted to the job environment to survive. + sed -E 's/^export +//' .gitlab/environment.env \ + | grep -E '^[A-Za-z_][A-Za-z0-9_]*=' >> "$GITHUB_ENV" 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:${RAILS_PORT:-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: Drive Zammad with this gem + shell: bash + run: | + source /etc/profile.d/rvm.sh + bundle exec ruby script/check_connection.rb + + - 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 + 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 0000000..63c96a2 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,45 @@ +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 # create the GitHub release and push the tag commit + 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 publishes a gem under a version nobody tagged and + # leaves a GitHub release pointing at one that does not exist. + - 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 spec:unit rubocop steep rbs_published + - uses: rubygems/release-gem@v1 diff --git a/.gitignore b/.gitignore index 002a2a1..bb396ef 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 8553cbe..740cb16 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 8c18f1a..7a2cc1a 100644 --- a/.rspec +++ b/.rspec @@ -1,2 +1,3 @@ +--require spec_helper --format documentation --color diff --git a/.rubocop.yml b/.rubocop.yml index 0ae18f9..fe861e4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,117 +1,82 @@ -# 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' + Description: 'Zammad allows multi-line bodies for a single condition.' 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' Enabled: false Layout/LeadingCommentSpace: - Description: 'Comments should start with a space.' - StyleGuide: 'https://github.com/bbatsov/ruby-style-guide#hash-space' Enabled: false 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] + # `of` is ActiveRecord's name for a batch size, see Collection#in_batches. + AllowedNames: [id, to, of] 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 -Style/BlockComments: - # Keep block comments (=begin ... =end) to allow for easy copy-pasting of examples. - Description: 'Do not use block comments.' +Naming/PredicateMethod: + # Established names from the resource API. `save` reports whether the record + # was stored; the rest return true on success. + AllowedMethods: + - save + - save! + - update + - update! + - destroy + +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 +88,56 @@ 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 + CountAsOne: ['array', 'hash', 'heredoc'] + Max: 12 + # Integration specs are end-to-end scenarios against a live Zammad. + Exclude: + - 'spec/integration/**/*' + +RSpec/MultipleExpectations: + Description: 'A few request assertions per example are clearer than splitting them.' + Max: 3 + Exclude: + - 'spec/integration/**/*' + +RSpec/DescribeMethod: + Exclude: + - 'spec/integration/**/*' RSpec/NestedGroups: - Max: 6 + Max: 4 -# 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 +RSpec/SpecFilePathFormat: + # Integration specs are grouped by the Zammad object they exercise, not by + # the class under test. + Exclude: + - 'spec/integration/**/*' + +RSpec/DescribeClass: + Exclude: + - 'spec/integration/**/*' + +RSpec/BeforeAfterAll: + Exclude: + - 'spec/integration/**/*' + +RSpec/LeakyLocalVariable: + # The integration specs deliberately share a record across ordered examples: + # each one asserts on what the previous step left behind. The coupling is + # pinned by `config.order = :defined` and every example that reads the record + # goes through `established!`, so a partial run says what is missing rather + # than failing on nil. + Exclude: + - 'spec/integration/**/*' + +RSpec/NoExpectationExample: + Exclude: + - 'spec/integration/**/*' diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index 20ec1c6..0000000 --- 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 0000000..7919852 --- /dev/null +++ b/.ruby-version @@ -0,0 +1 @@ +4.0.9 diff --git a/.yardopts b/.yardopts new file mode 100644 index 0000000..c10e67a --- /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 422138f..2c572df 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,243 @@ +# 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 + +- Minimum Ruby version is now 3.4. 3.0 through 3.2 are end-of-life, and 3.3 is in security + maintenance until March 2027. +- `Client.new` takes keyword arguments, so a configuration Hash has to be splatted: + `Client.new(**config)`. A positional Hash raises `ArgumentError`. +- An unknown client option raises `ArgumentError: unknown keyword` instead of being + ignored. +- `logger:` takes a `Logger` rather than a boolean flag. `logger: true` used to turn on + debug output to `$stderr`; pass `Logger.new($stderr)` for the same thing. Anything that + responds to `debug` works. +- `Collection#each` (`client.x.all`, `client.x.search`) now walks every page. Previously it + fetched a single page, so iterating stopped silently at 100 records for `all` and at + 10 for `search`. +- Collections are built up by chaining instead of by keyword arguments: + `all(per_page: 50)` is now `find_each(batch_size: 50)` or `page(1, per_page: 50)`, + `all(active: true)` is `search(...)` or `all.detect { ... }`, + `search(query: 'zammad')` is `search('zammad')`, + and `search(query: 'z', page: 2, per_page: 50)` is `search('z').page(2, per_page: 50)`. + `all` accepted those keywords and then discarded them, so its page size was always + 100 and its filters never reached the request. All of them now raise `ArgumentError`. +- `page(number, per_page)` with a block was replaced by `page(number, per_page: size)`, which + returns a new collection. `page_next` and `page_prev` were removed. +- `Collection#[]` was removed. It cost a request per index and ignored the page a + collection was limited to; use `first`, or `page(n, per_page: 1).first` for one record at an + offset. +- A collection fetches the endpoint's own page size rather than a fixed 100 — 1000 on the + index endpoints, 100 on `/api/v1/tickets`, 200 on a search. `page(n)` without `per_page:` + is a page of that size, so pin it with `page(n, per_page: 100)` where a persisted page + number has to keep meaning what it did. +- `client.on_behalf_of = 'login'` and `client.perform_on_behalf_of` were replaced by + `client.on_behalf_of('login')`, which returns a new client and also accepts a block. A + blank identifier raises `ArgumentError`. +- `ZammadAPI::ResourceNotFoundError` is now `ZammadAPI::UnknownResourceError`, freeing the + 404 case to be `ZammadAPI::NotFoundError`. +- `record.save` reports a validation failure as `false` and leaves the error in + `record.error`, instead of raising. `record.save!` is the raising form. Every other + failure still raises from both. `client..create` uses `save!`. +- `record.destroy` and `record.reload` raise for a record that was never saved, instead of + acting on an id it was merely built with: `client.groups.new(id: 99).destroy` sent + `DELETE /api/v1/groups/99`. +- `record.id = ...` raises `ZammadAPI::Error`. The id is what addresses the record, so a + staged one made `destroy` and `save` act on another record than the one they reported on. +- `record.destroy` marks the record `destroyed?`, and `persisted?` answers false for one. + 1.x left a destroyed record looking live. +- `record.attributes` and `record.changes` are deeply frozen, and `record.to_h` returns a + deep copy rather than a shallow one. Writing through either reader used to change what a + record reported without staging anything, so the next `save` did not send it. +- The `record.attributes=` writer was removed. An unknown name is an ordinary attribute + now, so `record.attributes = {name: 'Support'}` stages a change called `attributes` + that `save` sends to Zammad. Use `assign_attributes` or `update`. +- `ZammadAPI::Error` descends from `StandardError` instead of `RuntimeError`. +- `ResponseError#response` returns a `ZammadAPI::Response`, not a Faraday object, and + `#body` is the decoded payload rather than a raw JSON string. +- No Faraday exception escapes from a request any more: an unreachable host or a timeout + raises `ZammadAPI::ConnectionError` or `ZammadAPI::TimeoutError`, so a + `rescue Faraday::ConnectionFailed` stops matching. +- `ZammadAPI::ListBase`, `ListAll` and `ListSearch` were replaced by `ZammadAPI::Collection`. +- `ZammadAPI::Log` and `ZammadAPI::JsonHelper` were removed. Pass any `Logger` via `logger:`. +- `ZammadAPI::Dispatcher` was replaced by `ZammadAPI::ResourceProxy`. +- The resource readers on a client are plural: `client.tickets`, `client.users`, + `client.groups`, `client.organizations`, `client.ticket_articles`, + `client.ticket_priorities` and `client.ticket_states`. A resource is `Enumerable` over + every record of its kind, so `client.ticket.each` read as if it acted on one ticket. The + singular names raise `UnknownResourceError`, which lists the plural ones, and so does + `client.resource(:ticket)`. `client.resource_names` lists the plural names. +- The resource readers a client has are a fixed list. 1.x resolved `client.` to + `ZammadAPI::Resources::` through `const_get`; `client.role` now raises + `UnknownResourceError`. Hand a class of your own over instead, with + `client.resource(Role)`. +- The internal `new_instance` accessor was replaced by `new_record?` and `persisted?`, and + the instance-level `url` accessor by the class-level `resource_path`. Both old names now + raise `NoMethodError`. +- A reader for an attribute the record does not carry raises `NoMethodError` instead of + answering `nil`, so a typo no longer reads as `nil`. `record[:x]`, + `record.fetch(:x, nil)` and `record.key?(:x)` are the readers for an attribute that may + legitimately be absent, which it may be where Zammad serves a reduced object. +- `Collection#find` raises `ArgumentError` when given an id. On a collection it is + `Enumerable#find`, whose argument is an ifnone callable, so `client.tickets.all.find(1)` + answered with an `Enumerator` and made no request. Use `client.tickets.find(1)`, or + `detect { … }` for the block form. +- `search` raises `ZammadAPI::Error` on a resource Zammad routes no search endpoint for — + `ticket_states`, `ticket_priorities` and `ticket_articles` — instead of reaching a 404. +- A configuration that names more than one way to authenticate raises `ConfigurationError`. + 1.x accepted a token beside a user and password and sent the first in its order without + a word about the others. `from_env` and `with` drop the credentials an override replaces. +- `ticket.article(…)` is `ticket.add_article(…)`. A noun that sends a `POST` sat one letter + away from `ticket.articles`, which only reads. `article` is now an attribute reader like + any other, and the old call raises `NoMethodError`. + +### 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 and any `on_behalf_of` scope is carried over. +- `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 attributes every supported Zammad serves for it, 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`. +- An unknown resource name raises `UnknownResourceError` 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. +- Unit specs (`rake spec:unit`) run without a Zammad instance; the specs that need a live + server live in `spec/integration`, and run only where `TEST_URL` names one. +- CI runs RuboCop, Steep and the unit specs on every supported stable Ruby, and publishes + releases through RubyGems trusted publishing. +- The integration job waits for Zammad to answer before running specs, pins the Zammad ref + (overridable via `workflow_dispatch`), carries a timeout, uploads Zammad's logs on + failure, and runs `script/check_connection.rb` as a preflight. +- The integration suite no longer depends on spec file order to run Zammad's auto wizard, + and tolerates an instance that is already set up. + ## [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 +259,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 0000000..4f0a0d6 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,47 @@ +# 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 check_connection` | Drives a live Zammad end to end and prints a transcript | +| `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 and `check_connection` 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`, `rake spec` and `rake check_connection` 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 +export TEST_PASSWORD=test + +bundle exec rake check_connection # one linear pass, readable transcript +bundle exec rake spec:integration # the full spec suite +``` + +`check_connection` walks the documented workflows in order — create, find, update, reload, +pattern match, paginate, search, ticket with articles, attachment download, acting on +behalf of a user, and each error class — printing `ok` or `FAIL` per step and cleaning up +after itself. It stops early if a precondition fails, so a broken instance produces one +clear line rather than a cascade. + +CI runs both against a Zammad booted from source: the `integration` job clones Zammad, +starts it, waits for it to answer, runs `check_connection` as a fast preflight, then runs +the integration specs. Trigger it by hand from the Actions tab (`workflow_dispatch`) to +test against a specific Zammad ref. diff --git a/Gemfile b/Gemfile index 2d9e06b..a8d8416 100644 --- a/Gemfile +++ b/Gemfile @@ -1,17 +1,28 @@ +# 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' + gem 'yard', require: false +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 2b5b4f8..ba12f34 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.1.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.92.3) json (>= 2.3) language_server-protocol (~> 3.17.0.2) @@ -90,7 +144,29 @@ GEM regexp_parser (>= 2.0) rubocop (~> 1.86, >= 1.86.2) 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) @@ -99,21 +175,36 @@ GEM addressable (>= 2.8.0) crack (>= 0.3.2) hashdiff (>= 0.4.0, < 2.0.0) + yard (0.9.45) 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) + yard zammad_api! BUNDLED WITH - 2.6.9 + 4.0.20 diff --git a/LICENSE.md b/LICENSE.md index 17882e4..1b3f037 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 211469b..ed42d26 100644 --- a/README.md +++ b/README.md @@ -1,390 +1,770 @@ -# 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. 2.0 is a prerelease, and a prerelease has to be asked for: ```ruby -gem 'zammad_api' +gem 'zammad_api', '~> 2.0.0.alpha' +``` + +Or: + +```sh +gem install zammad_api --pre ``` -And then execute: +## Quick start - $ bundle +```ruby +require 'zammad_api' + +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'your-access-token' +) + +client.tickets.first(5).each { |ticket| puts ticket.title } -Or install it yourself as: +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'} +) - $ gem install zammad_api +ticket.add_article(body: 'Reset link sent.', type: 'note') +ticket.update(state: 'closed') -## Available objects +client.tickets.search('state.name:open').each { |open_ticket| puts open_ticket.number } -* user -* organization -* group -* ticket -* ticket_article -* ticket_state -* ticket_priority +begin + client.tickets.find(123_456) +rescue ZammadAPI::NotFoundError => e + warn e.server_message +end +``` -## Usage +The sections below cover [creating a client](#creating-a-client), +[records](#working-with-records), [collections](#collections) and +[error handling](#error-handling). -### Create instance +## Creating a client -#### Username/email and password +### 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 +``` + +`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). + +## Working with records + +### Create + +```ruby +user = client.users.new(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org') +user.save + +user.id # => 42 +user.email # => "nicole.braun@zammad.org" +``` + +Or in one call: + +```ruby +user = client.users.create(firstname: 'Nicole', lastname: 'Braun', email: 'nicole.braun@zammad.org') ``` -## Resource management +Attributes are a Hash, or anything that converts to one with `to_hash`. In a Rails +controller that is the permitted parameters: -Individual resources can be created, modified, saved, and destroyed. +```ruby +client.users.create(params.require(:user).permit(:login, :email, :password)) +``` -### Create object +### Fetch -With new and save: ```ruby -group = client.group.new( - name: 'Support', - note: 'Some note', -); -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 +``` + +`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 -group.id # id of record -group.name # 'Support' +```ruby +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 ``` -With create: +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. + +`attributes` and `changes` are frozen. Assign through a writer (`user.email = '...'`) to +stage a change. + +### Update + ```ruby -group = client.group.create( - name: 'Support', - note: 'Some note', -); +user = client.users.find(42) +user.firstname = 'Nicola' + +user.changed? # => true +user.changes # => {firstname: ["Nicole", "Nicola"]} -group.id # id of record -group.name # 'Support' +user.save # sends only the changed attributes ``` -### Fetch object +`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 -group = client.group.find(123) -puts group.inspect +user.update(firstname: 'Nicola', note: 'Renamed') # assigns, then saves +user.assign_attributes(firstname: 'Nicola') # assigns without saving ``` -### Update object + +### Saving and validation failures + +`save` returns whether the record was stored, and leaves a rejection in `error`: ```ruby -group = client.group.find(123) -group.name = 'Support 2' -group.save +group = client.groups.new(name: '') + +if group.save + puts group.id +else + warn group.error.server_message # => "Name is required" +end ``` -### Destroy object +Only a validation failure (HTTP 422) is reported this way. Every other failure raises. + +`save!` and `update!` raise on every failure, including validation: ```ruby -group = client.group.find(123) -group.destroy +group.save! # raises ZammadAPI::ValidationError +group.update!(name: '') # the same, in one call ``` -## Collection management +`create` raises on a validation failure, like `save!`. Use `new` and `save` to branch +instead. + +### Reload and destroy + +```ruby +user.reload # re-reads from Zammad, discarding unsaved changes +user.destroy # => true + +user.destroyed? # => true +user.persisted? # => false -A list of individual resources. +client.users.destroy(42) # delete by id, without fetching first +``` + +### Associations -### All +Zammad expands an association into a name beside the id, so those reads cost nothing: ```ruby -groups = client.group.all +ticket = client.tickets.find(1) + +ticket.customer # => "customer@example.com" +ticket.state # => "open" +ticket.group # => "Users" +ticket.customer_id # => 7 +``` -group1 = groups[0] -group1.note = 'Some note' -group1.save +The whole record behind one of those is a `find` by its id, which costs a request: -groups.each {|group| - p "group: #{group.name}" -} +```ruby +client.users.find(ticket.customer_id).firstname # => "Nicole" ``` -### Search +A foreign key that may be empty, such as a user's `organization_id`, is `nil` then, and +`find` needs an id: + ```ruby -groups = client.group.search(query: 'some name') +user.organization_id && client.organizations.find(user.organization_id) +``` + +### Articles and attachments -group1 = groups[0] -group1.note = 'Some note' -group1.save +```ruby +ticket.articles # => [TicketArticle, ...] +ticket.add_article(body: 'Reset link sent.', type: 'note') # => the created TicketArticle -groups.each {|group| - p "group: #{group.name}" -} +ticket.articles.each do |article| + article.attachments.each do |attachment| + File.binwrite(File.basename(attachment.filename), attachment.download) + end +end ``` -### All with pagination (beta) +`articles` is one request, and is fetched on each call. `download` returns the file +contents as a binary String. + +### Comparing and serializing + +Two records of the same kind with the same id are equal, so `uniq`, `Set` and `include?` +work as expected: ```ruby -groups = client.group.all +client.tickets.find(1) == client.tickets.find(1) # => true +``` + +`to_json` renders the attributes, and `as_json` returns them as a Hash: -groups.page(1,3) {|group| - p "group: #{group.name}" +```ruby +client.groups.find(1).to_json # => "{\"id\":1,\"name\":\"Support\"}" +``` - group.note = 'Some new note, inclued in page 1 with 3 per page' - group.save -} +### Pattern matching -groups.page(2,3) {|group| - p "group: #{group.name}" +Records implement `deconstruct_keys`, so they work with `case/in`: - group.note = 'Some new note, inclued in page 2 with 3 per page' - group.save -} +```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 ``` -### Search with pagination (beta) +## 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 -groups = client.group.search(query: 'some name') +client.tickets.each { |ticket| puts ticket.title } -groups.page(1,3) {|group| - p "group: #{group.name}" +# One request, for five records. +client.tickets.first(5) - group.note = 'Some new note, inclued in page 1 with 3 per page' - group.save -} +# Lazy chains stop fetching once they have enough. +client.tickets.lazy.select { |ticket| ticket.state == 'open' }.first(10) -groups.page(2,3) {|group| - p "group: #{group.name}" +# One array of records per request, e.g. for a bulk import. +client.tickets.in_batches(of: 50) { |tickets| import(tickets) } - group.note = 'Some new note, inclued in page 2 with 3 per page' - group.save -} +# 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"], ...] ``` -## Perform actions on behalf of another user +`client.tickets` and `client.tickets.all` are the same collection. Nothing is cached, so +iterating again fetches again. -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: +`client.tickets.find(1)` looks up by id. To find with a block, use `detect`. -> **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)). +### Searching ```ruby -client.on_behalf_of = 'some_login' +client.tickets.search('state.name:open').each { |ticket| puts ticket.title } +client.organizations.search('zammad').first(10) ``` -All following actions with the client will be performed on behalf of the user with the `login` "some_login". +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 +client.ticket_states.find_by(name: 'open') +client.ticket_priorities.select { it.active } +``` -To reset this back to regular requests just set `nil`: +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. ```ruby -client.on_behalf_of = nil +client.users.search('smith', role_ids: [2]) +client.tickets.search('printer', condition: {'ticket.group_id' => {operator: 'is', value: [2]}}) ``` -It's possible to perform only a block of actions on behalf of another user via: +A blank term raises `ArgumentError`. `search('*')` asks for every record. + +### Sorting + +`order` sorts on the server: ```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( - ... - ) -end +client.groups.order(:name) # ascending +client.organizations.order(name: :desc) +client.groups.order(:active, name: :desc) # by active, then by name descending +``` -# 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', - ], - }, -) +`/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: -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').order(created_at: :desc) ``` -List all new or open tickets: +### Pages + ```ruby -tickets = client.ticket.search(query: 'state.name:new OR state.name:open') +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 -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' +`count` on a search is one request. Every other collection is read page by page, because +an index endpoint reports no total: -tickets.each {|ticket| - p "ticket: #{ticket.number} - #{ticket.title}" -} +```ruby +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 ``` -Get all articles of a ticket: +## 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 -ticket = client.ticket.find(123) -articles = ticket.articles +support = client.on_behalf_of('agent@example.com') +support.tickets.create(title: 'Help', group: 'Users', customer_id: 1) +``` -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' +Or scoped to a block: -p "ticket: #{ticket.number} - #{ticket.title}" -articles.each {|article| - p "article: #{article.from} - #{article.subject}" -} +```ruby +client.on_behalf_of('agent@example.com') do |scoped| + scoped.tickets.find(1) +end ``` -Create an article for a ticket: +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 -ticket = client.ticket.find(123) +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.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 +``` -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', - ], +`ResponseError` exposes `response` (a `ZammadAPI::Response`) and, as shortcuts, `status`, +`body`, `headers` and `server_message`, plus `operation` and `resource_class`. + +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) ) +``` + +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 + +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') +``` + +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: + +```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'}) -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 -} +client.get('api/v1/tickets/1', headers: {'Accept-Language' => 'de-de'}) +``` + +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 +``` + +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 + +Modelled: tickets, ticket articles and their attachments, ticket states and priorities, +users, organizations and groups, the same set as 1.x. + +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. + +The [features roadmap][roadmap] shows what is in progress 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: -p "article: #{article.from} - #{article.subject}" +```ruby +client = ZammadAPI::Client.new( + url: 'https://zammad.example.com/', + http_token: 'token', + adapter: :net_http_persistent, + middleware: ->(connection) { connection.use(MyInstrumentation) } +) ``` -## Testing +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: -### Setup an (empty Zammad) test env +```ruby +ticket = client.tickets.find(1) + +ticket.title # String +ticket.organization_id # Integer? +ticket.titel # a type error: no such attribute is declared +``` +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 ``` -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 resource of your own needs an annotation: + +```ruby +roles = client.resource(Role) #: ZammadAPI::ResourceProxy[Role] ``` -### Execute client tests +## 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 -Run tests via `rake spec`. (Remember to export the vars above if you are running this in another shell.) +loop do + tickets = client.tickets.page(page, per_page: 50).to_a + break if tickets.empty? -## Publishing + import(tickets) -1. Update version in [version.rb](lib/zammad_api/version.rb). -2. Add release to [CHANGELOG.md](CHANGELOG.md) -3. Commit. -4. Test build. + page += 1 + File.write('cursor', page) +end ``` -> rake build -zammad_api 1.0.7 built to pkg/zammad_api-1.0.7.gem. + +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 +) ``` -5. Release + +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) ``` -> 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 +## Development + +```sh +bin/setup # bundle install, plus the overcommit git hooks +bundle exec rake # unit specs, RuboCop, Steep and the shipped signatures ``` -## Contributing +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 0000000..920325c --- /dev/null +++ b/ROADMAP.md @@ -0,0 +1,93 @@ +# 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 · 🚧 work in progress · ❌ not available + +## Resources + +| 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). + +## 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 work on it starts. + +| 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 diff --git a/Rakefile b/Rakefile index 4c774a2..f3085be 100644 --- a/Rakefile +++ b/Rakefile @@ -1,6 +1,67 @@ +# frozen_string_literal: true + require 'bundler/gem_tasks' +require 'fileutils' require 'rspec/core/rake_task' +require 'rubocop/rake_task' +require_relative 'script/live_target' + +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 and check_connection create and delete records, so +# neither has a default for where. Asked here as well as in each of them, so +# that a task which was asked to run against a live Zammad says why it did +# not rather than passing over specs that were left out. +desc 'Check that TEST_URL names the Zammad to run the live checks against' +task :live_target do + abort LiveTarget.unset_message('This task') if LiveTarget.url.nil? +end + +desc 'Drive the Zammad that TEST_URL names end to end with this gem' +task check_connection: :live_target do + sh 'ruby script/check_connection.rb' +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/Steepfile b/Steepfile new file mode 100644 index 0000000..19cf55c --- /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', 'timeout', '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/UPGRADING.md b/UPGRADING.md new file mode 100644 index 0000000..f58ff85 --- /dev/null +++ b/UPGRADING.md @@ -0,0 +1,156 @@ +# 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 `UnknownResourceError` | +| `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` | Renamed so it is not confused with a 404, now `NotFoundError` | +| `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 | + +## 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 diff --git a/bin/console b/bin/console new file mode 100755 index 0000000..dcbd7d1 --- /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 0000000..bc8f0ad --- /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 5cf5803..0000000 --- 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 608477d..7bbba75 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 0000000..aaa86db --- /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 b1d6c85..a38f807 100644 --- a/lib/zammad_api/client.rb +++ b/lib/zammad_api/client.rb @@ -1,65 +1,281 @@ -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" - end - ZammadAPI::Dispatcher.new(@transport, class_object) + # @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 - private + # @return [Config] the validated configuration, with credentials redacted + # from its +inspect+ output + def config = @transport.config - 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 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) - # check for token auth - return if @config[:http_token] && !@config[:http_token].empty? - return if @config[:oauth2_token] && !@config[:oauth2_token].empty? + resource_class = RESOURCES.fetch(name.to_sym) { raise UnknownResourceError, unknown_resource_message(name) } - if !@config[:user] || @config[:user].empty? - raise ConfigurationError, 'missing user in config' - end + @resources.fetch(resource_class) + end + + # @return [Array] every resource name this client supports + def resource_names = RESOURCES.keys + + # 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') + + # 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 + response = @transport.get('api/v1/version', operation: 'get the Zammad version') + response.decoded(:object, operation: 'get the Zammad version')[:version]&.to_s + 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) = raw(: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) = raw(:post, path, query: query, body: body, headers: headers) - return if @config[:password] && !@config[:password].empty? + # 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) = raw(:put, path, query: query, body: body, headers: headers) - raise ConfigurationError, 'missing password in config' + # 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) = raw(:delete, path, query: query, headers: headers) + + # @!endgroup + + # 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 + + # 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 + + def method_missing(name, *args) + return super if name.to_s.end_with?('=', '!', '?') + + raise UnknownResourceError, unknown_resource_message(name) 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 } + def respond_to_missing?(_name, _include_private = false) = false + + private + + def raw(method, path, query: nil, body: nil, headers: nil) + operation = "#{method.to_s.upcase} #{Transport.redact_path(path)}" + @transport.request(method, path, operation: operation, query: query, body: body, headers: headers) end + + def unknown_resource_message(name) = "Unknown resource #{name}, available resources are: #{RESOURCES.keys.join(', ')}" end end diff --git a/lib/zammad_api/collection.rb b/lib/zammad_api/collection.rb new file mode 100644 index 0000000..4d5ff3e --- /dev/null +++ b/lib/zammad_api/collection.rb @@ -0,0 +1,229 @@ +# 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 + @operation = "get .#{search ? 'search' : 'all'} of object" + @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.build(operation: @operation, page: number, resource_class: @resource_class) 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, operation: @operation, resource_class: @resource_class, query: @query.merge(page: number, per_page: @per_page)) + + response.decoded(:array, operation: @operation, resource_class: @resource_class).map { @resource_class.from_response(@transport, it) } + end + + def total_count + response = @transport.get(@path, operation: @operation, resource_class: @resource_class, 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 0000000..ecbaa2f --- /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 0000000..05846ae --- /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 07b311b..0000000 --- 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 4e07e1d..b49d651 100644 --- a/lib/zammad_api/errors.rb +++ b/lib/zammad_api/errors.rb @@ -1,62 +1,176 @@ -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 + # Formats the " ()" fragment shared by error + # messages, so every error reads the same way. + # + # @api private + # @param operation [String] + # @param resource_class [Class, nil] + # @return [String] + def self.subject_for(operation, resource_class) + resource_class ? "#{operation} (#{resource_class.name})" : operation + end + 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 + # @param operation [String] + # @param expected [Symbol, String] +:object+ or +:array+ + # @param actual [Class, String] what was decoded instead + # @param resource_class [Class, nil] + # @return [ParseError] + def self.build(operation:, expected:, actual:, resource_class: nil) + new("Can't #{subject_for(operation, resource_class)}: expected a JSON #{expected}, got #{actual}") + end + 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 + # @param operation [String] + # @param page [Integer] the page that repeated its predecessor + # @param resource_class [Class, nil] + # @return [PaginationError] + def self.build(operation:, page:, resource_class: nil) + new( + "Can't #{subject_for(operation, resource_class)}: page #{page} repeated page #{page - 1}, so the endpoint is " \ + 'ignoring the page parameter. If it serves every record in one response, read it with client.get instead.' + ) + end + 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 + + # @return [String] human readable description of what was attempted + attr_reader :operation + + # @return [Class, nil] the resource class involved, when applicable + attr_reader :resource_class + + # Returns the most specific error class for +response+ and instantiates it. + # + # @param response [Response] + # @param operation [String] + # @param resource_class [Class, nil] + # @return [ResponseError] + def self.build(response, operation:, resource_class: nil) + error_class = STATUS_ERRORS.fetch(response.status) { response.status >= 500 ? ServerError : ClientError } + + error_class.new(response: response, operation: operation, resource_class: resource_class) + end - def initialize(operation:, response:, resource_class: nil) + # @param operation [String] what was attempted + # @param response [Response, nil] + # @param resource_class [Class, nil] + # @param detail [String, nil] replaces the part of the message that would + # otherwise describe the response, for a failure that has none + def initialize(operation:, response: nil, resource_class: nil, detail: nil) @operation = operation @response = response @resource_class = resource_class - super(default_message) + @detail = detail + super(build_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 - def detail - body_error || "HTTP #{status}" - end + private - def body_error - return nil if body.to_s.strip.empty? + def build_message + "Can't #{Error.subject_for(operation, resource_class)}: #{detail}" + end - parsed = JSON.parse(body) - parsed.is_a?(Hash) ? parsed['error'] : nil - rescue JSON::ParserError - nil + def detail + @detail || server_message || (status ? "HTTP #{status}" : 'no response') end end + # Any 4xx response that has no more specific subclass. class ClientError < ResponseError; end + + # Any 5xx response. class ServerError < ResponseError; 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 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 fd8ca4c..0000000 --- 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 393c56a..0000000 --- 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 c8b692c..0000000 --- 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 fac7f2b..0000000 --- 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 b67ad26..0000000 --- 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 0000000..50c99a1 --- /dev/null +++ b/lib/zammad_api/resource_proxy.rb @@ -0,0 +1,204 @@ +# 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), operation: 'find object', resource_class: resource_class, query: { expand: true }) + + resource_class.from_response(@transport, response.decoded(:object, operation: 'find object', resource_class: resource_class)) + 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.new( + operation: "find object by #{params.keys.join(' and ')}", + resource_class: resource_class, + detail: 'no record matched' + ) + ) + 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), operation: 'destroy object', resource_class: resource_class) + 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#count) + def count(...) = all.count(...) + + # (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 8106a4d..f388c7d 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 2652c4d..1bc60e2 100644 --- a/lib/zammad_api/resources/base.rb +++ b/lib/zammad_api/resources/base.rb @@ -1,140 +1,244 @@ -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, operation: 'save object', resource_class: self.class, query: { expand: true }, body: @attributes) + else + unsaved = changes.transform_values(&:last) + return true if unsaved.empty? + + response = transport.put(member_path, operation: 'save object', resource_class: self.class, query: { expand: true }, body: unsaved) + end - def self.url(value) - @url = value + load_response!(response, 'save object') + 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 + response = transport.get(member_path, operation: 'reload object', resource_class: self.class, query: { expand: true }) + load_response!(response, 'reload object') + 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, operation: 'destroy object', resource_class: self.class) + @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, operation) + @attributes = frozen_attributes(response.decoded(:object, operation: operation, resource_class: self.class)) + @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 3a6a768..7c61bcb 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 671939f..5bb80db 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 448209b..b40f681 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, operation: 'get articles', resource_class: TicketArticle, query: { expand: true }) + + response.decoded(:array, operation: 'get articles', resource_class: TicketArticle).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 890918b..7d5d416 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 c3e06d9..70ef348 100644 --- a/lib/zammad_api/resources/ticket_article_attachment.rb +++ b/lib/zammad_api/resources/ticket_article_attachment.rb @@ -1,18 +1,40 @@ -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 + + # 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)) } + response = @transport.get( + "api/v1/ticket_attachment/#{segments.join('/')}", + operation: 'download attachment', + resource_class: self.class + ) - def download - response = @transport.get(url: "/api/v1/ticket_attachment/#{ticket_id}/#{article_id}/#{id}") - return response.body if response.status == 200 + response.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 c46534a..1d2910e 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 d05b75f..67c6e03 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 c5c667a..4632905 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 0000000..1ca2816 --- /dev/null +++ b/lib/zammad_api/response.rb @@ -0,0 +1,54 @@ +# 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] + # @param operation [String] + # @param resource_class [Class, nil] + # @return [Hash, Array] + # @raise [ParseError] when the body has another shape + def decoded(shape, operation:, resource_class: nil) + return body if body.is_a?(shape == :object ? Hash : Array) + + raise ParseError.build(operation: operation, expected: shape, actual: body.class, resource_class: resource_class) + end + end +end diff --git a/lib/zammad_api/transport.rb b/lib/zammad_api/transport.rb index 5ade333..1e68e89 100644 --- a/lib/zammad_api/transport.rb +++ b/lib/zammad_api/transport.rb @@ -1,63 +1,236 @@ +# 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 + # Methods that are retried: the ones that only read. A write that timed + # out may still have been applied, so it is not sent twice. + RETRIABLE_METHODS = %i[get head options].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 operation [String] description used in error messages + # @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 + # @param resource_class [Class, nil] used in error messages + # @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, operation:, query: nil, body: nil, headers: nil, resource_class: nil) + path = Transport.relative_path(path) + log_request(method, path, query, body, headers) + + started = Process.clock_gettime(Process::CLOCK_MONOTONIC) + response = decode(perform(method, path, query, body, headers)) + log_response(method, path, response, started) + return response if response.success? + + raise ResponseError.build(response, operation: operation, resource_class: resource_class) + rescue Faraday::TimeoutError => e + raise TimeoutError, "Can't #{operation}: request to #{Transport.redact_path(path)} timed out (#{e.message})" + rescue Faraday::SSLError => e + raise ConnectionError, "Can't #{operation}: TLS handshake with #{config.url} failed (#{e.message})" + rescue Faraday::ConnectionFailed => e + raise ConnectionError, "Can't #{operation}: #{config.url} is unreachable (#{e.message})" end + # The verb shorthands. + def get(path, operation:, **options) = request(:get, path, operation: operation, **options) + def post(path, operation:, **options) = request(:post, path, operation: operation, **options) + def put(path, operation:, **options) = request(:put, path, operation: operation, **options) + def delete(path, operation:, **options) = request(:delete, path, operation: operation, **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(method, path, query, body, headers) + logger.debug do + "Zammad API request: #{method.to_s.upcase} #{Transport.redact_path(path)}#{" 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(method, path, response, started) + duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round + logger.debug { "Zammad API response: #{method.to_s.upcase} #{Transport.redact_path(path)} -> #{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 4915c54..2bcc074 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/script/check_connection.rb b/script/check_connection.rb new file mode 100755 index 0000000..dfefb86 --- /dev/null +++ b/script/check_connection.rb @@ -0,0 +1,355 @@ +#!/usr/bin/env ruby +# frozen_string_literal: true + +# End-to-end check that this gem can actually drive a live Zammad instance. +# +# Deliberately standalone: it does not load the spec suite, so it still +# reports usefully when the specs themselves are what is broken. CI runs it +# after booting Zammad and before the integration specs, so a broken +# gem-to-Zammad link fails fast with a readable transcript. +# +# TEST_URL=https://zammad.example/ \ +# TEST_USER=admin@example.com \ +# TEST_PASSWORD=test \ +# bundle exec ruby script/check_connection.rb + +$LOAD_PATH.unshift File.expand_path('../lib', __dir__) + +require 'zammad_api' +require 'faraday' +require 'json' +require 'securerandom' +require_relative 'live_target' + +# No default for the URL. This script creates and deletes records, and +# `http://localhost:3000/` is where a Zammad under development listens. +URL = LiveTarget.url || abort(LiveTarget.unset_message('This script')) + +LOGIN = ENV['TEST_USER'] || 'admin@example.com' +PASSWORD = ENV['TEST_PASSWORD'] || 'test' +SUFFIX = SecureRandom.hex(4) + +@failures = [] +@group = nil +@ticket = nil + +# Runs one named check, printing its result and recording any failure. +def check(name) + detail = yield + puts format(' ok %-42s %s', name: name, detail: detail) + true +rescue => e + @failures << name + puts format(' FAIL %-42s %s: %s', name: name, error: e.class, message: e.message) + false +end + +# A check whose failure makes every later check meaningless, so the run stops +# rather than burying the cause under cascading NoMethodErrors. +def check!(name, &block) + return if check(name, &block) + + puts "\nAborting: '#{name}' is a precondition for the remaining checks." + finish +end + +def section(title) + puts "\n#{title}" +end + +def parse_json(body) + JSON.parse(body) +rescue JSON::ParserError + {} +end + +def cleanup + return if @group.nil? && @ticket.nil? + + section 'Cleanup' + check('destroy the ticket') { CLIENT.tickets.destroy(@ticket.id) } if @ticket + check('destroy the group') { CLIENT.groups.destroy(@group.id) } if @group +end + +def finish + cleanup + puts + if @failures.empty? + puts 'All checks passed.' + exit 0 + end + + puts "#{@failures.size} check(s) failed:" + @failures.each { puts " - #{it}" } + exit 1 +end + +puts "Checking #{URL} with zammad_api #{ZammadAPI::VERSION} on Ruby #{RUBY_VERSION}" + +section 'Instance setup' + +# The auto wizard creates the admin account. An instance that is already +# configured reports failure here, which is fine as long as it is set up. +check!('auto wizard or already configured') do + wizard = parse_json(Faraday.new(url: URL).get('api/v1/getting_started/auto_wizard').body) + next 'auto wizard ran' if wizard['auto_wizard_success'] + + # A configured Zammad requires authentication even for + # /api/v1/getting_started, so the setup state cannot be read from there. + # An authenticated request answers the only question that matters. + ZammadAPI::Client.new(url: URL, user: LOGIN, password: PASSWORD, retries: 0) + .groups.all.page(1, per_page: 1).to_a + 'already set up' +end + +CLIENT = ZammadAPI::Client.new(url: URL, user: LOGIN, password: PASSWORD, timeout: 30) + +section 'Client' + +check('credentials are redacted') do + raise 'password leaked into inspect output' if CLIENT.config.inspect.include?(PASSWORD) + + 'password absent from inspect output' +end + +check('derived client re-validates options') do + CLIENT.with(timeout: 45) + CLIENT.with(url: 'zammad.example.com') + raise 'expected ConfigurationError' +rescue ZammadAPI::ConfigurationError + 'invalid option rejected' +end + +section 'Records' + +check!('create a group') do + @group = CLIENT.groups.create(name: "smoke-#{SUFFIX}", note: 'created by check_connection.rb') + raise 'no id assigned' if @group.id.nil? + + "id=#{@group.id}" +end + +check('find it back') do + found = CLIENT.groups.find(@group.id) + raise "name mismatch: #{found.name}" if found.name != "smoke-#{SUFFIX}" + + found.name +end + +# Each of these reads back what Zammad holds and compares it: printing a +# value checks nothing. +check('update only the changed attribute') do + @group.note = 'updated' + raise 'change not staged' if !@group.changed? + raise "staged more than the note: #{@group.changes.keys.inspect}" if @group.changes.keys != [:note] + + @group.save + found = CLIENT.groups.find(@group.id) + raise "note was not saved: #{found.note.inspect}" if found.note != 'updated' + raise "name changed with it: #{found.name.inspect}" if found.name != "smoke-#{SUFFIX}" + + found.note +end + +check('reload discards local changes') do + @group.note = 'not saved' + note = @group.reload.note + raise "the staged value is still there: #{note.inspect}" if note != 'updated' + raise 'the record still reports a change' if @group.changed? + + note +end + +check('pattern match a record') do + case CLIENT.groups.find(@group.id) + in { name: String => name, active: true } then name + else raise 'record did not match the expected pattern' + end +end + +section 'Collections' + +check('iterate every group across pages') do + names = CLIENT.groups.all.map(&:name) + raise 'created group missing from .all' if !names.include?("smoke-#{SUFFIX}") + + "#{names.size} groups" +end + +check('fetch a single page') { "#{CLIENT.groups.all.page(1, per_page: 1).to_a.size} record" } + +check('lazy enumeration stops early') { CLIENT.groups.all.lazy.map(&:id).first(1).inspect } + +check('page by page') do + pages = 0 + CLIENT.groups.all.in_batches(of: 1) { pages += 1 } + "#{pages} page(s)" +end + +# The account this runs as is the one record a search is sure to have, and +# a search that answers with nothing does not raise. +check('search') do + hits = CLIENT.users.search(LOGIN).to_a + raise "no hit is #{LOGIN}, among #{hits.size}" if hits.none? { [it.login, it.email].include?(LOGIN) } + + "#{hits.size} hit(s)" +end + +check('find_by returns a record that matches') do + found = CLIENT.groups.find_by(name: "smoke-#{SUFFIX}") + raise 'no record found' if found.nil? + raise "found the wrong record: #{found.name}" if found.name != "smoke-#{SUFFIX}" + + "id=#{found.id}" +end + +# Two string attributes, of which find_by searches for one. Joined into a +# single term they match no column on an instance that searches through SQL +# LIKE rather than Elasticsearch, and a stubbed unit spec cannot see that. +check('find_by matches on two string attributes') do + group = CLIENT.groups.find(@group.id) + found = CLIENT.groups.find_by(name: group.name, note: group.note) + raise 'no record found' if found.nil? + raise "found the wrong record: #{found.name}" if found.id != group.id + + "id=#{found.id}" +end + +check('find_by returns nil for no match') do + found = CLIENT.groups.find_by(name: "no-such-group-#{SUFFIX}") + raise "expected nil, got #{found.inspect}" if !found.nil? + + 'nil' +end + +check('find_by! raises for no match') do + CLIENT.groups.find_by!(name: "no-such-group-#{SUFFIX}") + raise 'expected NotFoundError' +rescue ZammadAPI::NotFoundError + 'raised' +end + +check('exists?') do + raise 'the created group is missing' if !CLIENT.groups.exists?(@group.id) + raise 'a made-up id exists' if CLIENT.groups.exists?(0) + + 'true and false' +end + +check('pluck') do + names = CLIENT.groups.all.pluck(:name) + raise 'created group missing' if !names.include?("smoke-#{SUFFIX}") + + "#{names.size} names" +end + +check('empty? on a search with no hits') do + raise 'expected empty' if !CLIENT.groups.search("no-such-group-#{SUFFIX}").empty? + + 'true' +end + +check('order sorts an index endpoint that sorts') do + "#{CLIENT.groups.order(name: :desc).page(1, per_page: 2).to_a.size} record(s)" +end + +check('order refuses an index served in a fixed order') do + CLIENT.tickets.order(:title).to_a + raise 'expected ArgumentError' +rescue ArgumentError => e + e.message.split('.').first +end + +check('order sorts a search') do + "#{CLIENT.groups.search("smoke-#{SUFFIX}").order(:name, id: :desc).to_a.size} hit(s)" +end + +section 'Tickets' + +check!('create a ticket with its first article') do + @ticket = CLIENT.tickets.create( + title: "smoke ticket #{SUFFIX}", + group: 'Users', + customer: LOGIN, + article: { subject: 'smoke', body: 'created by check_connection.rb', type: 'note' } + ) + "number=#{@ticket.number}" +end + +check('read its articles') { "#{@ticket.articles.size} article(s)" } + +check('add another article') do + CLIENT.tickets.find(@ticket.id).add_article(subject: 'second', body: 'another one', type: 'note').id +end + +check('article count grew') do + count = @ticket.articles.size + raise "expected 2 articles, got #{count}" if count != 2 + + count +end + +check('attachment metadata and download') do + CLIENT.tickets.find(@ticket.id).add_article( + subject: 'with attachment', + body: 'see attachment', + type: 'note', + attachments: [{ filename: 'smoke.txt', data: ['smoke test 123'].pack('m0'), 'mime-type': 'text/plain' }] + ) + attachment = @ticket.articles.last.attachments.first + raise 'no attachment returned' if attachment.nil? + + # Once: each call is a full attachment fetch, and this transcript is meant to + # be a fast read of a freshly booted Zammad. + contents = attachment.download + raise "unexpected content: #{contents.inspect}" if contents != 'smoke test 123' + + "#{attachment.filename} (#{contents.bytesize} bytes)" +end + +section 'On behalf of another user' + +# Acting for the account the client is signed in as reads the same with the +# header or without it. Zammad answers 403 for a From that names nobody, so +# that is the answer which says the header arrived. +check('sends the From header') do + number = CLIENT.on_behalf_of(LOGIN) { |scoped| scoped.tickets.find(@ticket.id).number } + raise "read ticket #{number}, not #{@ticket.number}" if number != @ticket.number + + begin + CLIENT.on_behalf_of("nobody-#{SUFFIX}@example.com") { |scoped| scoped.tickets.find(@ticket.id) } + rescue ZammadAPI::AuthorizationError => e + next "number=#{number}, and status=#{e.status} for a user that does not exist" + end + raise 'a From header naming no user was accepted, so none was sent' +end + +check('block form leaves the outer client unscoped') do + CLIENT.on_behalf_of(LOGIN) { |scoped| scoped.groups.find(@group.id) } + CLIENT.groups.find(@group.id).name +end + +section 'Errors' + +check('missing record raises NotFoundError') do + CLIENT.groups.find(0) + raise 'expected NotFoundError' +rescue ZammadAPI::NotFoundError => e + "status=#{e.status}" +end + +check('invalid attributes raise a ClientError') do + CLIENT.groups.create({}) + raise 'expected a ClientError' +rescue ZammadAPI::ClientError => e + "status=#{e.status}" +end + +check('bad credentials raise AuthenticationError') do + ZammadAPI::Client.new(url: URL, user: 'nobody', password: 'wrong', retries: 0).groups.find(1) + raise 'expected AuthenticationError' +rescue ZammadAPI::AuthenticationError => e + "status=#{e.status}" +end + +finish diff --git a/script/live_target.rb b/script/live_target.rb new file mode 100644 index 0000000..0e9d8ea --- /dev/null +++ b/script/live_target.rb @@ -0,0 +1,32 @@ +# frozen_string_literal: true + +# The Zammad the live checks run against: the integration specs, `rake spec`, +# `rake check_connection` and script/check_connection.rb. +# +# Each of them creates and deletes records, so none has a default for where, +# and each asks here whether one was named, so that they agree on it. +# +# Plain Ruby with nothing required, so that the check script, which loads +# nothing of the spec suite on purpose, can load it too. +module LiveTarget + # What to write where TEST_URL is not set. A placeholder that cannot reach + # anything if it is pasted as it is: `.example` is reserved and never + # resolves, where `http://localhost:3000/` is a Zammad under development. + EXAMPLE = 'TEST_URL=https://zammad.example/ TEST_USER=admin@example.com TEST_PASSWORD=test' + + module_function + + # @return [String, nil] TEST_URL, or nil where it is unset or blank - + # Unicode spaces included, as Rails reads blank + def url + value = ENV['TEST_URL'].to_s + value.match?(/\A[[:space:]]*\z/) ? nil : value.strip + end + + # @param what [String] what the refusing check would have done, and to what + # @return [String] + def unset_message(what) + "TEST_URL is not set. #{what} creates and deletes records in the Zammad it runs against, so name one, " \ + "and make it one you can lose: #{EXAMPLE}" + end +end diff --git a/sig/vendor/faraday.rbs b/sig/vendor/faraday.rbs new file mode 100644 index 0000000..9db943e --- /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 0000000..3a9109a --- /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 0000000..47eb217 --- /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 0000000..6678af9 --- /dev/null +++ b/sig/zammad_api/client.rbs @@ -0,0 +1,49 @@ +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 + def method_missing: (Symbol, *untyped) -> untyped + def respond_to_missing?: (Symbol, ?bool) -> bool + + private + + def raw: (Symbol method, String path, ?query: Hash[untyped, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?) -> Response + def unknown_resource_message: (Symbol | String) -> String + end +end diff --git a/sig/zammad_api/collection.rbs b/sig/zammad_api/collection.rbs new file mode 100644 index 0000000..1c46031 --- /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 + @operation: 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 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 0000000..5814f17 --- /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 0000000..6e5d4cd --- /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 0000000..ab10718 --- /dev/null +++ b/sig/zammad_api/errors.rbs @@ -0,0 +1,73 @@ +module ZammadAPI + class Error < StandardError + def self.subject_for: (String operation, Class? resource_class) -> String + end + + class ConfigurationError < Error + end + + class UnknownResourceError < Error + end + + class TransportError < Error + end + + class ConnectionError < TransportError + end + + class TimeoutError < TransportError + end + + class ParseError < Error + def self.build: (operation: String, expected: (Symbol | String), actual: (Class | String), ?resource_class: Class?) -> ParseError + end + + class PaginationError < Error + def self.build: (operation: String, page: Integer, ?resource_class: Class?) -> PaginationError + end + + class ResponseError < Error + STATUS_ERRORS: Hash[Integer, singleton(ResponseError)] + + attr_reader response: Response? + attr_reader operation: String + attr_reader resource_class: Class? + + @detail: String? + + def self.build: (Response response, operation: String, ?resource_class: Class?) -> ResponseError + + def initialize: (operation: String, ?response: Response?, ?resource_class: Class?, ?detail: String?) -> void + def status: () -> Integer? + def body: () -> untyped + def headers: () -> Hash[String, String] + def server_message: () -> String? + + private + + def build_message: () -> String + def detail: () -> 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 0000000..5df87f7 --- /dev/null +++ b/sig/zammad_api/resource_proxy.rbs @@ -0,0 +1,42 @@ +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 count: (*untyped) ?{ (R) -> boolish } -> Integer + 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 0000000..6bb71c3 --- /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, String operation) -> 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 0000000..4bce2e5 --- /dev/null +++ b/sig/zammad_api/resources/resources.rbs @@ -0,0 +1,202 @@ +module ZammadAPI + # The attributes declared on each resource are the ones every Zammad the + # gem supports serves for it: the columns of its table, as they have been + # since Zammad 5, 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 0000000..2feb30e --- /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, operation: String, ?resource_class: Class?) -> untyped + end +end diff --git a/sig/zammad_api/transport.rbs b/sig/zammad_api/transport.rbs new file mode 100644 index 0000000..ab652c3 --- /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, operation: String, **untyped options) -> Response + def post: (String path, operation: String, **untyped options) -> Response + def put: (String path, operation: String, **untyped options) -> Response + def delete: (String path, operation: String, **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, operation: String, ?query: Hash[Symbol, untyped]?, ?body: untyped, ?headers: Hash[untyped, untyped]?, ?resource_class: Class?) -> 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: (Symbol, String, Hash[Symbol, untyped]?, untyped, Hash[untyped, untyped]?) -> void + def log_response: (Symbol, String, Response, Float) -> void + def loggable_body: (untyped body) -> String + def logger: () -> Logger + end +end diff --git a/spec/integration/authentication_spec.rb b/spec/integration/authentication_spec.rb new file mode 100644 index 0000000..7b0da48 --- /dev/null +++ b/spec/integration/authentication_spec.rb @@ -0,0 +1,29 @@ +# frozen_string_literal: true + +RSpec.describe ZammadAPI, 'authentication' do + it 'has a version number' do + expect(ZammadAPI::VERSION).not_to be_nil + end + + context 'with invalid credentials' do + let(:client) { Helper.client(user: 'not_existing', password: 'not_existing') } + + it 'raises AuthenticationError with the failing operation' do + expect { client.users.find(1) }.to raise_error(ZammadAPI::AuthenticationError) 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 'raises a ClientError, so both can be rescued together' do + expect { client.users.find(1) }.to raise_error(ZammadAPI::ClientError) + end + + %i[organizations groups ticket_priorities ticket_states].each do |resource| + it "raises for #{resource}" do + expect { client.public_send(resource).find(1) }.to raise_error(ZammadAPI::AuthenticationError) + end + end + end +end diff --git a/spec/zammad_api/resources/group_spec.rb b/spec/integration/group_spec.rb similarity index 83% rename from spec/zammad_api/resources/group_spec.rb rename to spec/integration/group_spec.rb index 6caf0d3..f3ab1b6 100644 --- a/spec/zammad_api/resources/group_spec.rb +++ b/spec/integration/group_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'group object basics' do +RSpec.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 + group_invalid = client.groups.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) + expect { group_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - group = client.group.new( + group = client.groups.new( name: name, assignment_timeout: 100, follow_up_assignment: false, @@ -37,6 +37,7 @@ end it 'save' do + group = established!(group, 'new with valid attributes') result = group.save expect(result).to be(true) @@ -76,7 +77,8 @@ end it 'find' do - group_lookup = client.group.find(group.id) + group = established!(group, 'new with valid attributes') + group_lookup = client.groups.find(group.id) expect(group_lookup.class).to eq(ZammadAPI::Resources::Group) expect(group_lookup.id).to eq(group.id) @@ -89,7 +91,8 @@ end it 'all' do - groups = client.group.all + group = established!(group, 'new with valid attributes') + groups = client.groups.all group_exists = nil groups.each do |local_group| @@ -109,7 +112,7 @@ group_exists.active = true group_exists.save - group_lookup = client.group.find(group.id) + group_lookup = client.groups.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") @@ -121,9 +124,9 @@ end it 'pagination with all' do - groups = client.group.all + groups = client.groups.all - expect(groups[0].class).to eq(ZammadAPI::Resources::Group) + expect(groups.first.class).to eq(ZammadAPI::Resources::Group) count = 0 groups.each do |local_group| @@ -133,13 +136,13 @@ expect(count).to eq(3) count = 0 - groups = client.group.all - groups.page(1, 3) do |local_group| + groups = client.groups.all + groups.page(1, per_page: 3).each 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| + groups.page(2, per_page: 3).each do |local_group| expect(local_group.class).to eq(ZammadAPI::Resources::Group) count += 1 end @@ -147,6 +150,7 @@ end it 'destroy' do + group = established!(group, 'new with valid attributes') result = group.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/organization_spec.rb b/spec/integration/organization_spec.rb similarity index 80% rename from spec/zammad_api/resources/organization_spec.rb rename to spec/integration/organization_spec.rb index 7851181..2bfd08c 100644 --- a/spec/zammad_api/resources/organization_spec.rb +++ b/spec/integration/organization_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'organization object basics' do +RSpec.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 + organization_invalid = client.organizations.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) + expect { organization_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - organization = client.organization.new( + organization = client.organizations.new( name: name, shared: false, note: '', @@ -33,6 +33,7 @@ end it 'save' do + organization = established!(organization, 'new with valid attributes') result = organization.save expect(result).to be(true) @@ -72,7 +73,8 @@ end it 'find' do - organization_lookup = client.organization.find(organization.id) + organization = established!(organization, 'new with valid attributes') + organization_lookup = client.organizations.find(organization.id) expect(organization_lookup.class).to eq(ZammadAPI::Resources::Organization) expect(organization_lookup.id).to eq(organization.id) @@ -85,7 +87,8 @@ end it 'all' do - organizations = client.organization.all + organization = established!(organization, 'new with valid attributes') + organizations = client.organizations.all organization_exists = nil organizations.each do |local_organization| @@ -104,7 +107,7 @@ organization_exists.active = true organization_exists.save - organization_lookup = client.organization.find(organization.id) + organization_lookup = client.organizations.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") @@ -115,9 +118,9 @@ end it 'pagination with all' do - organizations = client.organization.all + organizations = client.organizations.all - expect(organizations[0].class).to eq(ZammadAPI::Resources::Organization) + expect(organizations.first.class).to eq(ZammadAPI::Resources::Organization) count = 0 organizations.each do |local_organization| @@ -127,13 +130,13 @@ expect(count).to eq(2) count = 0 - organizations = client.organization.all - organizations.page(1, 3) do |local_organization| + organizations = client.organizations.all + organizations.page(1, per_page: 3).each 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| + organizations.page(2, per_page: 3).each do |local_organization| expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) count += 1 end @@ -141,7 +144,8 @@ end it 'search' do - organizations = client.organization.search(query: name) + organization = established!(organization, 'new with valid attributes') + organizations = client.organizations.search(name) organization_exists = nil organizations.each do |local_organization| @@ -160,7 +164,7 @@ organization_exists.active = false organization_exists.save - organization_lookup = client.organization.find(organization.id) + organization_lookup = client.organizations.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") @@ -171,9 +175,10 @@ end it 'pagination with search' do - organizations = client.organization.search(query: "#{name}-2") + organization = established!(organization, 'new with valid attributes') + organizations = client.organizations.search("#{name}-2") - expect(organizations[0].class).to eq(ZammadAPI::Resources::Organization) + expect(organizations.first.class).to eq(ZammadAPI::Resources::Organization) count = 0 organization_exists = nil @@ -194,13 +199,13 @@ 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| + organizations = client.organizations.search('zammad') + organizations.page(1, per_page: 3).each 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| + organizations.page(2, per_page: 3).each do |local_organization| expect(local_organization.class).to eq(ZammadAPI::Resources::Organization) count += 1 end @@ -208,6 +213,7 @@ end it 'destroy' do + organization = established!(organization, 'new with valid attributes') result = organization.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/ticket_priority_spec.rb b/spec/integration/ticket_priority_spec.rb similarity index 75% rename from spec/zammad_api/resources/ticket_priority_spec.rb rename to spec/integration/ticket_priority_spec.rb index 45f41a8..646eda2 100644 --- a/spec/zammad_api/resources/ticket_priority_spec.rb +++ b/spec/integration/ticket_priority_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'ticket priority object basics' do +RSpec.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 + ticket_priority_invalid = client.ticket_priorities.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) + expect { ticket_priority_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - ticket_priority = client.ticket_priority.new( + ticket_priority = client.ticket_priorities.new( name: name, note: '', active: true, @@ -31,6 +31,7 @@ end it 'save' do + ticket_priority = established!(ticket_priority, 'new with valid attributes') result = ticket_priority.save expect(result).to be(true) @@ -61,7 +62,8 @@ end it 'find' do - ticket_priority_lookup = client.ticket_priority.find(ticket_priority.id) + ticket_priority = established!(ticket_priority, 'new with valid attributes') + ticket_priority_lookup = client.ticket_priorities.find(ticket_priority.id) expect(ticket_priority_lookup.class).to eq(ZammadAPI::Resources::TicketPriority) expect(ticket_priority_lookup.id).to eq(ticket_priority.id) @@ -71,7 +73,8 @@ end it 'all' do - ticket_priorities = client.ticket_priority.all + ticket_priority = established!(ticket_priority, 'new with valid attributes') + ticket_priorities = client.ticket_priorities.all ticket_priority_exists = nil ticket_priorities.each do |local_ticket_priority| @@ -88,7 +91,7 @@ ticket_priority_exists.active = true ticket_priority_exists.save - ticket_priority_lookup = client.ticket_priority.find(ticket_priority.id) + ticket_priority_lookup = client.ticket_priorities.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") @@ -97,9 +100,9 @@ end it 'pagination with all' do - ticket_priorities = client.ticket_priority.all + ticket_priorities = client.ticket_priorities.all - expect(ticket_priorities[0].class).to eq(ZammadAPI::Resources::TicketPriority) + expect(ticket_priorities.first.class).to eq(ZammadAPI::Resources::TicketPriority) count = 0 ticket_priorities.each do |local_ticket_priority| @@ -109,18 +112,18 @@ expect(count).to eq(4) count = 0 - ticket_priorities = client.ticket_priority.all - ticket_priorities.page(1, 2) do |local_ticket_priority| + ticket_priorities = client.ticket_priorities.all + ticket_priorities.page(1, per_page: 2).each 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| + ticket_priorities.page(2, per_page: 2).each 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| + ticket_priorities.page(3, per_page: 2).each do |local_ticket_priority| expect(local_ticket_priority.class).to eq(ZammadAPI::Resources::TicketPriority) count += 1 end @@ -128,6 +131,7 @@ end it 'destroy' do + ticket_priority = established!(ticket_priority, 'new with valid attributes') result = ticket_priority.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/ticket_spec.rb b/spec/integration/ticket_spec.rb similarity index 84% rename from spec/zammad_api/resources/ticket_spec.rb rename to spec/integration/ticket_spec.rb index 1c95705..fb7a75d 100644 --- a/spec/zammad_api/resources/ticket_spec.rb +++ b/spec/integration/ticket_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'ticket object basics' do +RSpec.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 + ticket_invalid = client.tickets.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) + expect { ticket_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - ticket = client.ticket.new( + ticket = client.tickets.new( title: title, state: 'new', priority: '2 normal', @@ -42,6 +42,7 @@ end it 'save' do + ticket = established!(ticket, 'new with valid attributes') result = ticket.save expect(result).to be(true) @@ -80,11 +81,11 @@ articles = ticket.articles expect(articles.length).to eq(1) - expect(articles[0].class).to eq(ZammadAPI::Resources::TicketArticle) + expect(articles.first.class).to eq(ZammadAPI::Resources::TicketArticle) expect(articles[0].subject).to eq('some subject') expect(articles[0].body).to eq('some body') - ticket.article( + ticket.add_article( subject: 'some subject2', body: 'some body2', ) @@ -96,7 +97,7 @@ expect(articles[1].body).to eq('some body2') expect(articles[1].attachments.count).to eq(0) - ticket.article( + ticket.add_article( subject: 'some subject3', body: 'some body3', attachments: [ @@ -121,7 +122,8 @@ end it 'find' do - ticket_lookup = client.ticket.find(ticket.id) + ticket = established!(ticket, 'new with valid attributes') + ticket_lookup = client.tickets.find(ticket.id) expect(ticket_lookup.class).to eq(ZammadAPI::Resources::Ticket) expect(ticket_lookup.id).to eq(ticket.id) @@ -135,7 +137,8 @@ end it 'all' do - tickets = client.ticket.all + ticket = established!(ticket, 'new with valid attributes') + tickets = client.tickets.all ticket_exists = nil tickets.each do |local_ticket| @@ -156,7 +159,7 @@ ticket_exists.state = 'closed' ticket_exists.save - ticket_lookup = client.ticket.find(ticket.id) + ticket_lookup = client.tickets.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") @@ -169,8 +172,9 @@ end it 'pagination with all' do + ticket = established!(ticket, 'new with valid attributes') (1..10).each do |local_count| - client.ticket.create( + client.tickets.create( title: "test count ticket #{local_count}", state: 'new', priority: '2 normal', @@ -187,8 +191,8 @@ ) end - tickets = client.ticket.all - expect(tickets[0].class).to eq(ZammadAPI::Resources::Ticket) + tickets = client.tickets.all + expect(tickets.first.class).to eq(ZammadAPI::Resources::Ticket) count = 0 tickets.each do |local_ticket| expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) @@ -197,18 +201,18 @@ expect(count).to eq(12) count = 0 - tickets = client.ticket.all - tickets.page(1, 5) do |local_ticket| + tickets = client.tickets.all + tickets.page(1, per_page: 5).each 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| + tickets.page(2, per_page: 5).each 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| + tickets.page(3, per_page: 5).each do |local_ticket| expect(local_ticket.class).to eq(ZammadAPI::Resources::Ticket) count += 1 end @@ -216,6 +220,7 @@ end it 'destroy' do + ticket = established!(ticket, 'new with valid attributes') result = ticket.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/ticket_state_spec.rb b/spec/integration/ticket_state_spec.rb similarity index 84% rename from spec/zammad_api/resources/ticket_state_spec.rb rename to spec/integration/ticket_state_spec.rb index d672398..8b62bc4 100644 --- a/spec/zammad_api/resources/ticket_state_spec.rb +++ b/spec/integration/ticket_state_spec.rb @@ -1,22 +1,22 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'ticket state object basics' do +RSpec.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 + ticket_state_invalid = client.ticket_states.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) + expect { ticket_state_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - ticket_state = client.ticket_state.new( + ticket_state = client.ticket_states.new( name: name, state_type: 'new', next_state_id: nil, @@ -30,7 +30,7 @@ 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.key?(:state_type_id)).to be(false) expect(ticket_state.next_state_id).to be_nil expect(ticket_state.ignore_escalation).to be(false) expect(ticket_state.note).to eq('') @@ -38,6 +38,7 @@ end it 'save' do + ticket_state = established!(ticket_state, 'new with valid attributes') result = ticket_state.save expect(result).to be(true) @@ -91,7 +92,8 @@ end it 'find' do - ticket_state_lookup = client.ticket_state.find(ticket_state.id) + ticket_state = established!(ticket_state, 'new with valid attributes') + ticket_state_lookup = client.ticket_states.find(ticket_state.id) expect(ticket_state_lookup.class).to eq(ZammadAPI::Resources::TicketState) expect(ticket_state_lookup.id).to eq(ticket_state.id) @@ -108,7 +110,8 @@ end it 'all' do - ticket_states = client.ticket_state.all + ticket_state = established!(ticket_state, 'new with valid attributes') + ticket_states = client.ticket_states.all ticket_state_exists = nil ticket_states.each do |local_ticket_state| @@ -132,7 +135,7 @@ ticket_state_exists.active = true ticket_state_exists.save - ticket_state_lookup = client.ticket_state.find(ticket_state.id) + ticket_state_lookup = client.ticket_states.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") @@ -147,9 +150,9 @@ end it 'pagination with all' do - ticket_states = client.ticket_state.all + ticket_states = client.ticket_states.all - expect(ticket_states[0].class).to eq(ZammadAPI::Resources::TicketState) + expect(ticket_states.first.class).to eq(ZammadAPI::Resources::TicketState) count = 0 ticket_states.each do |local_ticket_state| @@ -159,18 +162,18 @@ expect(count).to be >= 7 count = 0 - ticket_states = client.ticket_state.all - ticket_states.page(1, 3) do |local_ticket_state| + ticket_states = client.ticket_states.all + ticket_states.page(1, per_page: 3).each 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| + ticket_states.page(2, per_page: 3).each 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| + ticket_states.page(3, per_page: 3).each do |local_ticket_state| expect(local_ticket_state.class).to eq(ZammadAPI::Resources::TicketState) count += 1 end @@ -178,6 +181,7 @@ end it 'destroy' do + ticket_state = established!(ticket_state, 'new with valid attributes') result = ticket_state.destroy expect(result).to be(true) diff --git a/spec/zammad_api/resources/user_spec.rb b/spec/integration/user_spec.rb similarity index 86% rename from spec/zammad_api/resources/user_spec.rb rename to spec/integration/user_spec.rb index a82b94b..41fd018 100644 --- a/spec/zammad_api/resources/user_spec.rb +++ b/spec/integration/user_spec.rb @@ -1,6 +1,6 @@ -require 'spec_helper' +# frozen_string_literal: true -describe ZammadAPI, 'user object basics' do +RSpec.describe ZammadAPI, 'user object basics' do client = Helper.client random = Helper.random @@ -10,16 +10,16 @@ user = nil it 'new with invalid attributes' do - user_invalid = client.user.new + user_invalid = client.users.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) + expect { user_invalid.save! }.to raise_error(ZammadAPI::ClientError) end it 'new with valid attributes' do - user = client.user.new( + user = client.users.new( firstname: firstname, lastname: lastname, email: email, @@ -44,6 +44,7 @@ end it 'save' do + user = established!(user, 'new with valid attributes') result = user.save expect(result).to be(true) @@ -88,7 +89,8 @@ end it 'find' do - user_lookup = client.user.find(user.id) + user = established!(user, 'new with valid attributes') + user_lookup = client.users.find(user.id) expect(user_lookup.class).to eq(ZammadAPI::Resources::User) expect(user_lookup.id).to eq(user.id) @@ -105,7 +107,8 @@ end it 'all' do - users = client.user.all + user = established!(user, 'new with valid attributes') + users = client.users.all user_exists = nil users.each do |local_user| @@ -128,7 +131,7 @@ expect(user_exists.updated_by).to eq('admin@example.com') user_exists.save - user_lookup = client.user.find(user.id) + user_lookup = client.users.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") @@ -146,7 +149,7 @@ it 'pagination with all' do (1..10).each do |local_count| - client.user.create( + client.users.create( firstname: "firstname#{local_count}", lastname: "lastname#{local_count}", email: "customer_email#{local_count}@example.com", @@ -157,9 +160,9 @@ ) end - users = client.user.all + users = client.users.all - expect(users[0].class).to eq(ZammadAPI::Resources::User) + expect(users.first.class).to eq(ZammadAPI::Resources::User) count = 0 users.each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) @@ -168,19 +171,19 @@ expect(count).to eq(15) count = 0 - users = client.user.all - users.page(1, 4) do |local_user| + users = client.users.all + users.page(1, per_page: 4).each 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| + users.page(2, per_page: 5).each 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| + users.page(1, per_page: 200).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end @@ -188,7 +191,8 @@ end it 'search' do - users = client.user.search(query: firstname) + user = established!(user, 'new with valid attributes') + users = client.users.search(firstname) user_exists = nil users.each do |local_user| @@ -210,7 +214,7 @@ user_exists.active = false user_exists.save - user_lookup = client.user.find(user.id) + user_lookup = client.users.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") @@ -224,9 +228,10 @@ end it 'pagination with search' do - users = client.user.search(query: firstname) + user = established!(user, 'new with valid attributes') + users = client.users.search(firstname) - expect(users[0].class).to eq(ZammadAPI::Resources::User) + expect(users.first.class).to eq(ZammadAPI::Resources::User) count = 0 user_exists = nil @@ -250,13 +255,13 @@ 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| + users = client.users.search(firstname) + users.page(1, per_page: 3).each 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| + users.page(2, per_page: 3).each do |local_user| expect(local_user.class).to eq(ZammadAPI::Resources::User) count += 1 end @@ -264,6 +269,7 @@ end it 'destroy' do + user = established!(user, 'new with valid attributes') # wait until zammad scheduler wrote some entries to activity stream # to have some references and not allow users to delete sleep 12 diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 6c318c4..f6cb116 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,50 +1,84 @@ +# 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 + $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' +# Unit specs run entirely against stubs; integration specs opt back out below. +require 'webmock/rspec' +require 'zammad_api' + +Dir[File.expand_path('support/**/*.rb', __dir__)].each { require it } RSpec.configure do |config| - config.include WebMock::API - config.include WebMock::Matchers -end + config.include ClientHelper + config.include LifecycleState, :integration -require 'zammad_api' + config.expect_with(:rspec) { it.syntax = :expect } + config.mock_with(:rspec) { it.verify_partial_doubles = true } -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 + config.disable_monkey_patching! + config.warnings = false + config.filter_run_when_matching :focus + config.example_status_persistence_file_path = 'tmp/rspec_status.txt' + config.shared_context_metadata_behavior = :apply_to_host_groups - def self.client(params = {}) - ZammadAPI::Client.new( - url: params[:url] || config[:url], - user: params[:user] || config[:user], - password: params[:password] || config[:password], - ) + # Specs are grouped by what they need: unit specs run against WebMock stubs + # and never touch the network, integration specs need a live Zammad. + # + # The integration specs also walk a record through its lifecycle across + # ordered examples, so they are pinned to definition order, whatever + # `--seed` or `--order` says. Unit specs stay order-independent. + config.define_derived_metadata(file_path: %r{/spec/unit/}) { it[:unit] = true } + config.define_derived_metadata(file_path: %r{/spec/integration/}) do |metadata| + metadata[:integration] = true + metadata[:order] = :defined end - # 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 - end - - url_auto_wizard = '/api/v1/getting_started/auto_wizard' - response = conn.get url_auto_wizard - data = JSON.parse(response.body) + # Integration specs write to the Zammad they are pointed at, so they run + # only where TEST_URL names one: see Helper.target. Left out rather than + # failed, so that a bare `rspec` is the unit specs and nothing else, and + # said once so that nobody takes it for a run of them. + # + # The notice goes out when the first of them is loaded rather than before + # the suite: RSpec runs no suite hook for a run that selected nothing, + # which is what `rspec spec/integration` is without a TEST_URL. + # + # A run that selected nothing but them fails, though, so that a CI job + # that lost its TEST_URL does not pass with `0 examples, 0 failures`. A + # bare `rspec` still runs the unit specs, so this fires only where + # everything selected was left out. + config.fail_if_no_examples = true - return true if data['auto_wizard_success'] + if Helper.target.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 + end - raise "Unable to start auto wizard: #{response.body}" + # The instance has to have an admin account before anything can + # authenticate. Doing this from a hook rather than from one spec file keeps + # the suite independent of file order. + config.before(:each, :integration) do + Helper.ensure_configured! end - def self.random - rand(99_999_999).to_s + # Integration specs need the real network, so WebMock steps aside for them. + config.around(:each, :integration) do |example| + WebMock.allow_net_connect! + WebMock.disable! + 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 0000000..1709c28 --- /dev/null +++ b/spec/support/client_helper.rb @@ -0,0 +1,37 @@ +# 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 + + # Zammad's own answer with a body that cannot be read: it says it is JSON, + # and what arrived of it is not. + # + # @return [Hash] arguments for WebMock's +to_return+ + def unreadable_json_response(status: 200) + { status: status, body: '{"id":1,"na', headers: { 'Content-Type' => 'application/json' } } + end +end diff --git a/spec/support/integration_helper.rb b/spec/support/integration_helper.rb new file mode 100644 index 0000000..e46dead --- /dev/null +++ b/spec/support/integration_helper.rb @@ -0,0 +1,136 @@ +# frozen_string_literal: true + +require 'securerandom' +require_relative '../../script/live_target' + +# Helpers for integration specs, which need a reachable Zammad instance. +class Helper + class SetupError < StandardError; end + + # The Zammad the integration specs run against, where one was named. + # + # There is no default. These specs run the auto wizard and then create, + # change and delete records, a bare `rspec` loads them along with the unit + # specs, and `http://localhost:3000/` is where a Zammad under development + # listens. Where to write is for whoever runs them to say. + # + # Asked of {LiveTarget}, which rake and script/check_connection.rb ask + # as well, so that the three agree on whether a target was named. + # + # @return [String, nil] nil when TEST_URL is not set + def self.target = LiveTarget.url + + # Where no TEST_URL is set, a URL nothing answers at stands in for it. The + # spec files build their client while they are loaded, which is before + # RSpec has left their examples out, so this cannot raise; the examples + # never run, and {.ensure_configured!} refuses them if they are made to. + # `.invalid` is reserved for names that never resolve. + UNSET_URL = 'http://test-url-not-set.invalid/' + + def self.config + { + url: target || UNSET_URL, + user: ENV['TEST_USER'] || 'admin@example.com', + password: ENV['TEST_PASSWORD'] || 'test' + } + end + + def self.client(**overrides) + settings = config + ZammadAPI::Client.new( + url: overrides.fetch(:url, settings[:url]), + user: overrides.fetch(:user, settings[:user]), + password: overrides.fetch(:password, settings[:password]), + **overrides.except(:url, :user, :password) + ) + end + + # Makes sure the instance has an admin account, running Zammad's auto wizard + # once per suite. + # + # Memoized and idempotent, so it does not matter which spec file happens to + # run first, and re-running the suite against an already configured instance + # is not an error. The failure is memoized alongside the success, so that a + # TEST_URL with nothing behind it is probed once rather than once per + # example, each probe waiting out its timeouts. + def self.ensure_configured! + raise SetupError, 'TEST_URL is not set, so there is no Zammad to run the integration specs against' if target.nil? + return true if @ensure_configured + raise @setup_failure if @setup_failure + + begin + auto_wizard? || verify_setup_done! + @ensure_configured = true + rescue SetupError => e + @setup_failure = e + raise + end + end + + # The body is asked about only where it is a JSON object: valid JSON that + # is not one - `null`, a list, a number - is no answer. Anything but an + # object saying the wizard ran leaves {.verify_setup_done!} to decide. + # + # @return [Boolean] whether the auto wizard ran now + # @raise [SetupError] when the instance cannot be reached at all + def self.auto_wizard? + response = connection.get('api/v1/getting_started/auto_wizard') + body = parse(response.body) + body.is_a?(Hash) && body['auto_wizard_success'] == true + rescue Faraday::Error => e + # Wrapped the way {.verify_setup_done!} wraps its failure, so that a + # Zammad that never came up reaches every example as a SetupError naming + # the URL rather than as a bare Faraday exception. + raise SetupError, + "Zammad at #{config[:url]} could not be reached: the setup check failed to connect " \ + "(#{e.class}: #{e.message}). Set TEST_URL to a running instance." + end + + # A configured Zammad requires authentication even for + # /api/v1/getting_started, so the setup state cannot be read from there. + # Proving that the configured credentials work answers the only question + # that matters here. + def self.verify_setup_done! + ZammadAPI::Client.new(**config).groups.all.page(1, per_page: 1).to_a + true + rescue ZammadAPI::Error => e + raise SetupError, + "Zammad at #{config[:url]} is not usable: the auto wizard did not run and " \ + "authenticating as #{config[:user]} failed (#{e.class}: #{e.message})" + end + + # Finite timeouts matter here: a TEST_URL that accepts the connection but + # never answers would otherwise hang the integration job until the CI + # timeout rather than failing the setup check. + def self.connection + Faraday.new(url: config[:url], request: { open_timeout: 10, timeout: 30 }) + end + + def self.parse(body) + JSON.parse(body) + rescue JSON::ParserError + {} + end + + def self.random + SecureRandom.random_number(99_999_999).to_s + end + + private_class_method :verify_setup_done!, :connection, :parse +end + +# Each integration spec file walks one record through its lifecycle - new, +# save, find, destroy - and every step asserts on what the previous one left +# behind, so the record is shared across ordered examples. +# +# That coupling holds as long as the whole file runs in definition order. +# Under `--only-failures` or `-e 'save'` it does not, and this names the +# cause where the example would otherwise fail on nil. +module LifecycleState + def established!(record, example) + return record if record + + raise "this example continues the record built by '#{example}', which did not run in this process. " \ + 'These examples share one record and have to run as a whole file, in definition order.' + end +end diff --git a/spec/support/strong_parameters.rb b/spec/support/strong_parameters.rb new file mode 100644 index 0000000..2df64e5 --- /dev/null +++ b/spec/support/strong_parameters.rb @@ -0,0 +1,28 @@ +# frozen_string_literal: true + +# What `ActionController::Parameters` is to this gem, without Rails: not a +# Hash, converting to one with String keys where it was permitted and +# refusing where it was not, and printing everything it holds. +# +# The real one answers `to_hash` with plain Hashes all the way down, so this +# one converts what it holds of its own kind. +class StrongParameters + class Unfiltered < ArgumentError; end + + # @param values [Hash] the parameters, which may also be written as + # keywords: `StrongParameters.new(name: 'Support')` + def initialize(values = {}, permitted: true, **keywords) + @values = values.merge(keywords) + @permitted = permitted + end + + def to_hash + raise Unfiltered, 'unable to convert unpermitted parameters to hash' if !@permitted + + @values.to_h { |key, value| [key.to_s, value.is_a?(self.class) ? value.to_hash : value] } + end + + def to_s = @values.to_s + + def inspect = "#<#{self.class.name} #{@values.inspect} permitted: #{@permitted}>" +end diff --git a/spec/typed/sig/usage.rbs b/spec/typed/sig/usage.rbs new file mode 100644 index 0000000..bae828d --- /dev/null +++ b/spec/typed/sig/usage.rbs @@ -0,0 +1,34 @@ +# 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.readers_of_group: (ZammadAPI::Client) -> Array[String] + def self.owners_of_group: (ZammadAPI::Client) -> Array[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 0000000..f36f307 --- /dev/null +++ b/spec/typed/usage.rb @@ -0,0 +1,78 @@ +# 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.readers_of_group(client) = client.users.search('smith', group_ids: { 2 => ['read'] }).map(&:login) + + def self.owners_of_group(client) = client.users.search('smith', group_ids: [2]).map(&:login) + + 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 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 0000000..b6b7c31 --- /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 0000000..d1860f3 --- /dev/null +++ b/spec/unit/zammad_api/client_spec.rb @@ -0,0 +1,464 @@ +# 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 'the singular names the readers had in 1.x' do + [:ticket].each do |old_name| + it "does not answer ##{old_name}" do + expect { unit_client.public_send(old_name) } + .to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource #{old_name}, available resources are: groups, /) + end + 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 'unknown methods' do + it 'raises UnknownResourceError for an unknown resource name' do + expect { unit_client.unicorn }.to raise_error(ZammadAPI::UnknownResourceError, /Unknown resource unicorn/) + end + + it 'does not claim to respond to it' do + expect(unit_client).not_to respond_to(:unicorn) + end + + it 'still raises NoMethodError for a bang method' do + expect { unit_client.save! }.to raise_error(NoMethodError) + end + + it 'still raises NoMethodError for a predicate' do + expect { unit_client.valid? }.to raise_error(NoMethodError) + end + + it 'stays usable in array operations that rely on to_ary' do + client = unit_client + expect([client].flatten).to eq([client]) + 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, "Can't GET api/v1/roles: 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, "Can't GET api/v1/roles: 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, email address or id of a user, got #{blank.inspect}") + 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 0000000..a47b201 --- /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, /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 0000000..f7e9bb0 --- /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 0000000..aa683f2 --- /dev/null +++ b/spec/unit/zammad_api/resource_proxy_spec.rb @@ -0,0 +1,445 @@ +# 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 query and the resource 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("Can't find object by name and active (ZammadAPI::Resources::Group): no record matched") + 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 '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 0000000..a42019d --- /dev/null +++ b/spec/unit/zammad_api/resources/base_spec.rb @@ -0,0 +1,547 @@ +# 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 '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 0000000..f6c5343 --- /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 0000000..c44dea1 --- /dev/null +++ b/spec/unit/zammad_api/resources/ticket_spec.rb @@ -0,0 +1,105 @@ +# 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, /Can't get articles \(ZammadAPI::Resources::TicketArticle\): 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 '#article' do + it 'reads the article staged for the next save' do + ticket.article = { body: 'reply' } + + expect(ticket.article).to eq(body: 'reply') + 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 0000000..2c265b8 --- /dev/null +++ b/spec/unit/zammad_api/response_error_spec.rb @@ -0,0 +1,179 @@ +# 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, {}), operation: 'find object') + 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' }), + 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 'prefers error_human, which Zammad intends for end users' do + error = described_class.build( + response(422, { error: 'Validation failed', error_human: 'Name is required' }), + operation: 'save object' + ) + expect(error.message).to eq("Can't save object: 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'), + 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 the status when the body has no error key' do + error = described_class.build(response(400, { foo: 'bar' }), operation: 'find object') + expect(error.message).to eq("Can't find object: HTTP 400") + end + + it 'falls back to the status when the error value is empty' do + error = described_class.build(response(500, { error: '' }), operation: 'find object') + expect(error.message).to eq("Can't find object: HTTP 500") + end + + it 'reports a missing response' do + expect(described_class.new(operation: 'find object').message) + .to eq("Can't find object: no response") + end + + it 'omits the resource class when none was supplied' do + error = described_class.build(response(404, { error: 'nope' }), operation: 'find object') + expect(error.message).to eq("Can't find object: nope") + end + end + + describe 'accessors' do + subject(:error) do + described_class.build( + response(404, { error: 'nope' }, 'x-request-id' => 'abc'), + operation: 'find object', + resource_class: ZammadAPI::Resources::User + ) + 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 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 '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(operation: 'find object') + 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(operation: 'find object by name', detail: 'no record 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), operation: 'find object').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 0000000..0731ded --- /dev/null +++ b/spec/unit/zammad_api/response_spec.rb @@ -0,0 +1,81 @@ +# 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, operation: 'find object')).to eq(a: 1) + end + + it 'returns an array body when one is expected' do + expect(build(body: [{ a: 1 }]).decoded(:array, operation: 'get list')).to eq([{ a: 1 }]) + end + + it 'raises when an object was expected but a list arrived' do + expect { build(body: []).decoded(:object, operation: 'find object') } + .to raise_error(ZammadAPI::ParseError, "Can't find object: expected a JSON object, got Array") + end + + it 'raises when a list was expected but an object arrived' do + expect { build(body: {}).decoded(:array, operation: 'get list') } + .to raise_error(ZammadAPI::ParseError, "Can't get list: expected a JSON array, got Hash") + end + + it 'raises when the body was never JSON' do + expect { build(body: '', raw_body: '').decoded(:object, operation: 'find object') } + .to raise_error(ZammadAPI::ParseError, /got String/) + end + + it 'names the resource class in the message' do + expect { build(body: []).decoded(:object, operation: 'find object', resource_class: ZammadAPI::Resources::User) } + .to raise_error(/\(ZammadAPI::Resources::User\)/) + end + + it 'accepts an empty list' do + expect(build(body: []).decoded(:array, operation: 'get list')).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 0000000..1ebb820 --- /dev/null +++ b/spec/unit/zammad_api/transport_spec.rb @@ -0,0 +1,568 @@ +# frozen_string_literal: true + +require 'pp' + +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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test', 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', operation: 'test') + 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', operation: 'test', 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', operation: 'test') }.to raise_error(ArgumentError) + expect(a_request(:any, //)).not_to have_been_made + end + end + + # The path is printed in the log, in the message of a timeout and in the + # operation a raw request is named by, 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', operation: 'test', 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', operation: 'test', 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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test') + 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', operation: 'find object') } + .to raise_error(ZammadAPI::NotFoundError, "Can't find object: nope") + end + + it 'includes the resource class in the message' do + stub_request(:get, url).to_return(json_response({ error: 'nope' }, status: 404)) + expect { unit_transport.get('api/v1/groups', operation: 'find object', resource_class: ZammadAPI::Resources::Group) } + .to raise_error(/\(ZammadAPI::Resources::Group\)/) + 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', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError, %r{Can't find object: request to 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', operation: 'find object') } + .to raise_error(ZammadAPI::TimeoutError, %r{request to 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', operation: 'find object') } + .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', operation: 'find object') } + .to raise_error(ZammadAPI::ConnectionError, %r{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', operation: 'find object') } + .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', operation: 'test') + 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', operation: 'test') + 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', operation: 'test') }.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', operation: 'test') } + .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', operation: 'test', 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', operation: 'test', 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', operation: 'test') } + .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', operation: 'test') } + .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', operation: 'test') + + expect(seen).to eq("zammad_api-ruby/#{ZammadAPI::VERSION}") + 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', operation: 'test').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', operation: 'test') + 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', operation: 'test', 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', operation: 'test') } + .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', operation: 'test', 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', operation: 'test', 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, operation: 'test') + 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', + operation: 'test', + 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 9f6b73f..0000000 --- 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 b335088..0000000 --- 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 29eb956..0000000 --- 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/list_base_spec.rb b/spec/zammad_api/resources/list_base_spec.rb deleted file mode 100644 index c7018e3..0000000 --- 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/transport_spec.rb b/spec/zammad_api/transport_spec.rb deleted file mode 100644 index 66032e5..0000000 --- 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 6616717..0000000 --- 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 7b09454..7d9d251 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