elasticsearch-test-runner 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 139cdbecff8a7f080c63ce718ceee51b4718629d604b2a70f49e456fb898abee
4
+ data.tar.gz: f5917106b5f1a17c1e74b664c1a16c485e4d0e623e1e2e5293f20954fb5d0ea5
5
+ SHA512:
6
+ metadata.gz: b592e11ccbeae18bb9fbd0fe5760caea1bda3ed891895073854dfc11861f6d7c386dd6b973b3807598565d6da81332be6839bcae4ad64d75b8693645bea08a2d
7
+ data.tar.gz: db573c22f278bef0e57a1fc3a79fd7c9ab296504d108b2b2cded3648057c2e3df5f59230ef41a14c7fe61a92e3c10cfee247734e8f45125560d4adb1a7a9c659
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-02-22
4
+
5
+ - Initial release
data/CODE_OF_CONDUCT ADDED
@@ -0,0 +1 @@
1
+ See: https://www.elastic.co/community/codeofconduct
data/CONTRIBUTING.md ADDED
@@ -0,0 +1,17 @@
1
+ # Contributing
2
+
3
+ After checking out the repo, run `bin/setup` to install dependencies. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
4
+
5
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
6
+
7
+ The process for contributing to any of the [Elasticsearch](https://github.com/elasticsearch) repositories is similar:
8
+
9
+ 1. It is best to do your work in a separate Git branch. This makes it easier to synchronise your changes with [`rebase`](http://mislav.uniqpath.com/2013/02/merge-vs-rebase/).
10
+
11
+ 2. Make sure your changes don't break any existing tests, and that you add tests for both bugfixes and new functionality. If you want to examine the test coverage, you can generate a report by running `COVERAGE=true rake test:all`.
12
+
13
+ 3. **Sign the contributor license agreement.**
14
+ Please make sure you have signed the [Contributor License Agreement](https://www.elastic.co/contributor-agreement/). We are not asking you to assign copyright to us, but to give us the right to distribute your code without restriction. We ask this of all contributors in order to assure our users of the origin and continuing existence of the code. You only need to sign the CLA once.
15
+
16
+ 4. Submit a pull request.
17
+ Push your local changes to your forked copy of the repository and submit a pull request. In the pull request, describe what your changes do and mention the number of the issue where discussion has taken place, eg “Closes #123″.
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Elasticsearch Ruby Tests Runner
2
+ Copyright 2024 Elasticsearch B.V.
data/README.md ADDED
@@ -0,0 +1,56 @@
1
+ # Elasticsearch Tests Runner
2
+
3
+ This gem is a tool for Elasticsearch Ruby clients to run the [Elasticsearch Clients Tests](https://github.com/elastic/elasticsearch-clients-tests). The Client tests project is a test suite in the YAML format. It defines a set of actions and expectations to run against Elasticsearch. The are designed to run with Elasticsearch clients, with the goal to reuse across different Elasticsearch clients in different programming languages.
4
+
5
+ This is the Ruby version and is being used in the [elasticsearch](https://github.com/elastic/elasticsearch-ruby) and [elasticsearch-serverless](https://github.com/elastic/elasticsearch-serverless-ruby/) Ruby clients.
6
+
7
+ ## Installation
8
+
9
+ Add the gem to the application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'elasticsearch-test-runner', git: 'git@github.com:elastic/es-test-runner-ruby.git'
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ To start using the library, add this to your code:
18
+
19
+ ```ruby
20
+ # Require the library
21
+ require 'elasticsearch/tests/test_runner'
22
+ # Define a path where the test files are being stored:
23
+ tests_path = File.expand_path('./tmp', __dir__)
24
+ # Instantiate an Elasticsearch client
25
+ client = Elasticsearch::Client.new
26
+ # Instantiate and run the test runner:
27
+ Elasticsearch::Tests::TestRunner.new(client, tests_path).run
28
+ ```
29
+
30
+ [The tests](https://github.com/elastic/elasticsearch-clients-tests) are designed for the Elasticsearch REST API and the Elasticsearch Serverless REST API. If you pass in an `ElasticsearchServerless::Client`, it will only run the tests that have the `requires.serverless: true` statement. Otherwise, it will only run the ones with `requires.stack: true`.
31
+
32
+ You can optionally pass in an object that implements Ruby's Logger to the `TestRunner` initializer. This will log more information, particularly useful in the case of errors where it'll log stacktraces for exceptions and more:
33
+
34
+ ```ruby
35
+ logger = Logger.new($stdout)
36
+ logger.level = Logger::WARN unless ENV['DEBUG']
37
+
38
+ Elasticsearch::Tests::TestRunner.new(client, tests_path, logger).run
39
+ ```
40
+
41
+ You can **download the YAML test files** from [the clients tests project](https://github.com/elastic/elasticsearch-clients-tests) with the following code:
42
+
43
+ ```ruby
44
+ require 'elasticsearch/tests/downloader'
45
+ Elasticsearch::Tests::Downloader::run(tests_path)
46
+ ```
47
+
48
+ Additionally, you can run the rake task `rake es_tests:download` included in `lib/elasticsearch/tasks`.
49
+
50
+ ## Development
51
+
52
+ See [CONTRIBUTING](./CONTRIBUTING.md).
53
+
54
+ ## License
55
+
56
+ This software is licensed under the [Apache 2 license](./LICENSE). See [NOTICE](./NOTICE).
data/Rakefile ADDED
@@ -0,0 +1,20 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ require 'bundler/gem_tasks'
19
+ task default: %i[]
20
+ Dir.glob('lib/elasticsearch/tasks/**/*.rake').each { |f| import f }
@@ -0,0 +1,51 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ # frozen_string_literal: true
19
+
20
+ require_relative 'lib/elasticsearch/tests/version'
21
+
22
+ Gem::Specification.new do |spec|
23
+ spec.name = 'elasticsearch-test-runner'
24
+ spec.email = ['client-libs@elastic.co']
25
+ spec.version = Elasticsearch::Tests::VERSION
26
+ spec.authors = ['Elastic Client Library Maintainers']
27
+ spec.licenses = ['Apache-2.0']
28
+ spec.summary = 'Tool to test Elasticsearch clients against the YAML clients test suite.'
29
+ spec.homepage = 'https://www.elastic.co/guide/en/elasticsearch/client/ruby-api/current/index.html'
30
+ spec.description = 'A test runner for the Elasticsearch clients YAML test suite, used in the elasticsearch and elasticsearch-serverless gems.'
31
+ spec.metadata['homepage_uri'] = spec.homepage
32
+ spec.metadata['changelog_uri'] = 'https://github.com/elastic/es-test-runner-ruby/blob/main/CHANGELOG.md'
33
+ spec.metadata['source_code_uri'] = 'https://github.com/elastic/es-test-runner-ruby/tree/main'
34
+
35
+ spec.required_ruby_version = '>= 3.0'
36
+
37
+ # Specify which files should be added to the gem when it is released.
38
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
39
+ spec.files = Dir.chdir(__dir__) do
40
+ `git ls-files -z`.split("\x0").reject do |f|
41
+ (File.expand_path(f) == __FILE__) ||
42
+ f.start_with?(*%w[bin/ test/ spec/ features/ .git appveyor Gemfile])
43
+ end
44
+ end
45
+ spec.bindir = 'exe'
46
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
47
+ spec.require_paths = ['lib']
48
+
49
+ spec.add_development_dependency 'elasticsearch'
50
+ spec.add_development_dependency 'elasticsearch-serverless'
51
+ end
@@ -0,0 +1,25 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ require 'elasticsearch/tests/downloader'
18
+
19
+ namespace :es_tests do
20
+ desc 'Download YAML test files'
21
+ task :download do |_, args|
22
+ tests_path = args[:path] || File.expand_path('../../tmp', __dir__)
23
+ Elasticsearch::Tests::Downloader::run(tests_path)
24
+ end
25
+ end
@@ -0,0 +1,216 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ require_relative 'printer'
18
+
19
+ module Elasticsearch
20
+ module Tests
21
+ #
22
+ # The module in charge of actually running actions and matching expected results with actual response results.
23
+ #
24
+ module CodeRunner
25
+ include Elasticsearch::Tests::Printer
26
+
27
+ COMPARATORS = {
28
+ 'lt' => '<',
29
+ 'lte' => '<=',
30
+ 'gt' => '>',
31
+ 'gte' => '>='
32
+ }.freeze
33
+
34
+ # The main functionality in the test runner, run actions with the client from YAML `do`
35
+ # specifications. These are function calls to the Elasticsearch clients.
36
+ #
37
+ def do_action(action)
38
+ client = @client
39
+ action = action.first if action.is_a?(Array)
40
+ method, params = action.is_a?(String) ? [action, {}] : action.first
41
+
42
+ # Get the namespace client if the method is namespaced
43
+ if method.include?('.')
44
+ arrayed_method = method.split('.')
45
+ client = @client.send(arrayed_method.first)
46
+ method = arrayed_method.last
47
+ end
48
+
49
+ @response = client.send(method.to_sym, process_params(params))
50
+ @response
51
+ rescue StandardError => e
52
+ raise e
53
+ end
54
+
55
+ # Code for matching expectations and response
56
+ #
57
+ def do_match(action)
58
+ k, v = action['match'].first
59
+ v = instance_variable_get(v.gsub('$', '@')) if v.is_a?(String) && v.include?('$')
60
+ result = search_in_response(k)
61
+
62
+ if !result.nil? && (
63
+ result == v ||
64
+ (result.respond_to?(:include?) && result.include?(v)) ||
65
+ match_regexp(v, result)
66
+ )
67
+ print_success
68
+ else
69
+ print_match_failure(action)
70
+ end
71
+ end
72
+
73
+ def match_regexp(expected, result)
74
+ expected.is_a?(String) && expected.match?(/^\//) && result.match?(Regexp.new(expected.gsub('/', '')))
75
+ end
76
+
77
+ def do_length(action)
78
+ k, v = action['length'].first
79
+ result = search_in_response(k).count
80
+ if result && result == v
81
+ print_success
82
+ else
83
+ print_failure(action, @response)
84
+ end
85
+ end
86
+
87
+ #
88
+ # The specified key exists and has a true value (ie not 0, false, undefined, null)
89
+ # action - { 'is_true' => field } or { 'is_true' => '' }
90
+ #
91
+ def is_true(action)
92
+ if @response.respond_to?(:body) && !@response&.nil? && ['', []].include?(action['is_true'])
93
+ print_success
94
+ return
95
+ end
96
+
97
+ response_value = search_in_response(action['is_true']) unless [true, false].include?(@response)
98
+ if @response == true || !response_value.nil?
99
+ print_success
100
+ else
101
+ print_failure(action, @response)
102
+ end
103
+ end
104
+
105
+ def is_false(action)
106
+ response_value = search_in_response(action['is_false']) unless [true, false].include? @response
107
+ if @response == false || response_value.nil? || [false, 'false'].include?(response_value)
108
+ print_success
109
+ else
110
+ print_failure(action, @response)
111
+ end
112
+ end
113
+
114
+ #
115
+ # Used for comparing gte (greater or equal than), gt (greater than), lte (less or equal than)
116
+ # and lt (less than)
117
+ # action - { 'gte' => { 'key' => value } }
118
+ #
119
+ def compare(action)
120
+ operator, value = action.first
121
+ result = search_in_response(value.keys.first)
122
+ if result&.send(COMPARATORS[operator], value[value.keys.first])
123
+ print_success
124
+ else
125
+ print_failure(action, @response)
126
+ end
127
+ end
128
+
129
+ # When the yaml test has a set instruction, set an instance variable with that value coming
130
+ # from the response.
131
+ def set_variable(action)
132
+ k, v = action['set'].first
133
+ instance_variable_set("@#{v}", search_in_response(k))
134
+ end
135
+
136
+ private
137
+
138
+ # Given a key coming from a test definition, search the response body for a matching value.
139
+ #
140
+ def search_in_response(keys)
141
+ if (match = /\$([a-z]+)/.match(keys))
142
+ return @response.send(match[1])
143
+ end
144
+
145
+ if keys.include?('.')
146
+ key = split_and_parse_key(keys)
147
+ return find_value_in_document(key, @response.body)
148
+ end
149
+
150
+ @response[keys]
151
+ end
152
+
153
+ # Symbolizes keys and replaces parameters defined as dynamic in the yaml spec (e.g. $body)
154
+ # with the corresponding variable set in set_variable
155
+ #
156
+ def process_params(params)
157
+ params = params.transform_keys(&:to_sym)
158
+ params.map do |key, param|
159
+ params[key] = process_params(param) if param.is_a?(Hash)
160
+ set_param_variable(params, key, param)
161
+ param.map { |param| set_param_variable(params, key, param) } if param.is_a?(Array)
162
+ end
163
+ params
164
+ end
165
+
166
+ def set_param_variable(params, key, param)
167
+ params[key] = instance_variable_get(param.gsub('$', '@')) if param.is_a?(String) && param.include?('$')
168
+ end
169
+
170
+ # Given a list of keys, find the value in a recursively nested document.
171
+ #
172
+ # @param [ Array<String> ] chain The list of nested document keys.
173
+ # @param [ Hash ] document The document to find the value in.
174
+ #
175
+ # @return [ Object ] The value at the nested key.
176
+ #
177
+ def find_value_in_document(chain, document)
178
+ return document[chain] unless chain.is_a?(Array)
179
+ return document[chain[0]] unless chain.size > 1
180
+
181
+ # a number can be a string key in a Hash or indicate an element in a list
182
+ if document.is_a?(Hash)
183
+ find_value_in_document(chain[1..], document[chain[0].to_s]) if document[chain[0].to_s]
184
+ elsif document[chain[0]]
185
+ find_value_in_document(chain[1..], document[chain[0]]) if document[chain[0]]
186
+ end
187
+ end
188
+
189
+ # Given a string representing a nested document key using dot notation,
190
+ # split it, keeping escaped dots as part of a key name and replacing
191
+ # numerics with a Ruby Integer.
192
+ #
193
+ # For example:
194
+ # "joe.metadata.2.key2" => ['joe', 'metadata', 2, 'key2']
195
+ # "jobs.0.node.attributes.ml\\.enabled" => ["jobs", 0, "node", "attributes", "ml\\.enabled"]
196
+ #
197
+ # @param [ String ] chain The list of nested document keys.
198
+ # @param [ Hash ] document The document to find the value in.
199
+ #
200
+ # @return [ Array<Object> ] A list of the nested keys.
201
+ #
202
+ def split_and_parse_key(key)
203
+ key.split(/(?<!\\)\./).reject(&:empty?).map do |key_part|
204
+ case key_part
205
+ when /^\.\$/ # For keys in the form of .$key
206
+ key_part.gsub(/^\./, '')
207
+ when /\A[-+]?[0-9]+\z/
208
+ key_part.to_i
209
+ else
210
+ key_part.gsub('\\', '')
211
+ end
212
+ end.reject { |k| k == '$body' }
213
+ end
214
+ end
215
+ end
216
+ end
@@ -0,0 +1,64 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ require 'open-uri'
18
+
19
+ module Elasticsearch
20
+ module Tests
21
+ # Module for downloading the test files
22
+ module Downloader
23
+ class << self
24
+ FILENAME = 'tests.zip'.freeze
25
+
26
+ def run(path, branch = 'main')
27
+ delete_files(path)
28
+ url = "https://api.github.com/repos/elastic/serverless-clients-tests/zipball/#{branch}"
29
+ if download_tests(url)
30
+ puts "Successfully downloaded #{FILENAME}"
31
+ else
32
+ warn "[!] Couldn't download #{FILENAME}"
33
+ return
34
+ end
35
+ unzip_file(path)
36
+ File.delete(FILENAME)
37
+ end
38
+
39
+ def download_tests(url)
40
+ File.open(FILENAME, 'w') do |downloaded_file|
41
+ uri = URI.parse(url)
42
+ uri.open('Accept' => 'application/vnd.github+json') do |artifact_file|
43
+ downloaded_file.write(artifact_file.read)
44
+ end
45
+ end
46
+ File.exist?(FILENAME)
47
+ end
48
+
49
+ private
50
+
51
+ def unzip_file(path)
52
+ puts 'Unzipping files'
53
+ puts path
54
+ `unzip #{FILENAME} -d #{path}/`
55
+ puts 'Removing zip file'
56
+ end
57
+
58
+ def delete_files(path)
59
+ FileUtils.rm_rf(Dir.glob("#{path}/**/*"), secure: true)
60
+ end
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,23 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ module Elasticsearch
19
+ module Tests
20
+ class TestFailure < StandardError; end
21
+ class TestError < StandardError; end
22
+ end
23
+ end
@@ -0,0 +1,80 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ require_relative 'errors'
18
+
19
+ module Elasticsearch
20
+ module Tests
21
+ #
22
+ # Functions to print out test results, errors, summary, etc.
23
+ #
24
+ module Printer
25
+ def print_success
26
+ response = if [true, false].include? @response
27
+ @response
28
+ else
29
+ @response.status
30
+ end
31
+ puts "🟢 #{@file} #{@title} passed. Response: #{response}"
32
+ end
33
+
34
+ def print_failure(action, response)
35
+ puts "🔴 #{@file} #{@title} failed"
36
+ puts "Expected result: #{action}" # TODO: Show match/length differently
37
+ if response.is_a?(ElasticsearchServerless::API::Response)
38
+ puts 'Response:'
39
+ pp response.body
40
+ else
41
+ pp response
42
+ end
43
+ raise Elasticsearch::Tests::TestFailure
44
+ end
45
+
46
+ def print_match_failure(action)
47
+ keys = action['match'].keys.first
48
+ value = action['match'].values.first
49
+ message = <<~MSG
50
+ 🔴 #{@file} #{@title} failed
51
+ Expected: { #{keys}: #{value} }
52
+ Actual : { #{keys}: #{search_in_response(action['match'].keys.first)} }
53
+ MSG
54
+ raise Elasticsearch::Tests::TestFailure.new(message)
55
+ end
56
+
57
+ def print_error(error)
58
+ puts "❌ ERROR: #{@file} #{@title} failed\n"
59
+ logger.error error.display
60
+ backtrace = error.backtrace.join("\n")
61
+ logger.error "#{backtrace}\n"
62
+ raise error
63
+ end
64
+
65
+ def self.display_errors(errors)
66
+ puts "+++ ❌ Errors/Failures: #{errors.count}"
67
+ errors.map do |error|
68
+ puts "* Test: #{error[:file]}\n #{error[:error].message}"
69
+ pp error[:error].backtrace.join("$/\n") if ENV['DEBUG']
70
+ puts
71
+ end
72
+ end
73
+
74
+ def self.display_summary(tests_count, errors_count, start_time)
75
+ puts "--- 🧪 Tests: #{tests_count} | Passed: #{tests_count - errors_count} | Failed: #{errors_count}"
76
+ puts "--- ⏲ Elapsed time: #{Time.at(Time.now - start_time).utc.strftime("%H:%M:%S")}"
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,111 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ require_relative 'code_runner'
19
+
20
+ module Elasticsearch
21
+ module Tests
22
+ #
23
+ # Represents a test, which is initialized in the test runner when iterating through the YAML
24
+ # files. Each YAML file can have more than one test.
25
+ # When a test is executed it runs the setup, actions (and matches) and finally the teardown stage.
26
+ #
27
+ class Test
28
+ include Elasticsearch::Tests::CodeRunner
29
+
30
+ def initialize(yaml, file, client)
31
+ @setup = extract_setup!(yaml)
32
+ @teardown = extract_teardown!(yaml)
33
+ @title = yaml.first.keys.first
34
+ @actions = yaml.first[@title]
35
+ @file = test_filename(file)
36
+ @client = client
37
+ end
38
+
39
+ def execute
40
+ begin
41
+ run_setup
42
+ run_actions
43
+ ensure
44
+ run_teardown
45
+ end
46
+ end
47
+
48
+ def run_actions
49
+ return unless @actions
50
+
51
+ @actions.map { |action| run_action(action) }
52
+ end
53
+
54
+ def run_action(action)
55
+ definition = action.keys.first
56
+
57
+ case definition
58
+ when 'do'
59
+ do_action(action['do'])
60
+ when 'set'
61
+ set_variable(action)
62
+ when 'match'
63
+ do_match(action)
64
+ when 'length'
65
+ do_length(action)
66
+ when 'is_true'
67
+ is_true(action)
68
+ when 'is_false'
69
+ is_false(action)
70
+ when 'gt', 'gte', 'lt', 'lte'
71
+ compare(action)
72
+ end
73
+ end
74
+
75
+ def run_setup
76
+ return unless @setup
77
+
78
+ @setup.map do |step|
79
+ do_action(step['do']) if step['do']
80
+ end
81
+ end
82
+
83
+ def run_teardown
84
+ return unless @teardown
85
+
86
+ @teardown['teardown'].map { |step| do_action(step['do']) }
87
+ end
88
+
89
+ def count
90
+ @actions.length
91
+ end
92
+
93
+ def test_filename(file)
94
+ name = file.split('/')
95
+ "#{name[-2]}/#{name[-1]}"
96
+ end
97
+
98
+ def extract_setup!(yaml)
99
+ yaml.map.with_index do |a, i|
100
+ yaml.delete_at(i) if a.keys.first == 'setup'
101
+ end.compact.first&.[]('setup')
102
+ end
103
+
104
+ def extract_teardown!(yaml)
105
+ yaml.map.with_index do |a, i|
106
+ yaml.delete_at(i) if a.keys.first == 'teardown'
107
+ end.compact.first
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,93 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ require 'logger'
19
+ require 'yaml'
20
+ require_relative './test'
21
+ require_relative './printer'
22
+
23
+ module Elasticsearch
24
+ module Tests
25
+ # Main YAML test runner
26
+ class TestRunner
27
+ LOGGER = Logger.new($stdout)
28
+ LOGGER.level = Logger::WARN unless ENV['DEBUG']
29
+
30
+ def initialize(client, path = nil, logger = nil)
31
+ @client = client
32
+ @serverless = (defined?(::ElasticsearchServerless) && client.is_a?(::ElasticsearchServerless::Client))
33
+ @path = path || File.expand_path('./tmp', __dir__)
34
+ @logger = logger || LOGGER
35
+ end
36
+
37
+ def run(test_files = [])
38
+ raise 'Couldn\'t find test files. Run `Elasticsearch::Tests::Downloader::run(tests_path)` to download the tests' unless File.directory?(@path)
39
+
40
+ @test_files = select_test_files(test_files)
41
+ run_the_tests
42
+ Elasticsearch::Tests::Printer::display_errors(@errors) unless @errors.empty?
43
+ Elasticsearch::Tests::Printer::display_summary(@tests_count, @errors.count, @start_time)
44
+ end
45
+
46
+ def run_the_tests
47
+ @start_time = Time.now
48
+ @tests_count = 0
49
+ @errors = []
50
+
51
+ @test_files.map do |test_file|
52
+ build_and_run_tests(test_file)
53
+ rescue Psych::SyntaxError => e
54
+ @errors << { error: e, file: test_file }
55
+ @logger.warn("YAML error in #{test_file}")
56
+ @logger.warn e
57
+ rescue StandardError => e
58
+ @errors << { error: e, file: test_file }
59
+ @logger.debug e
60
+ end
61
+ end
62
+
63
+ def build_and_run_tests(test_file)
64
+ yaml = YAML.load_stream(File.read(test_file))
65
+ requires = extract_requires!(yaml).compact.first['requires']
66
+ return unless (requires['serverless'] == true && @serverless) ||
67
+ (requires['stack'] == true && !@serverless)
68
+
69
+ test = Elasticsearch::Tests::Test.new(yaml, test_file, @client)
70
+ test.execute
71
+ @tests_count += test.count
72
+ rescue StandardError => e
73
+ raise e
74
+ end
75
+
76
+ def select_test_files(test_files)
77
+ if test_files.empty?
78
+ Dir.glob("#{@path}/**/*.yml")
79
+ else
80
+ test_files.map do |test_file|
81
+ "#{@path}/tests/#{test_file}"
82
+ end
83
+ end
84
+ end
85
+
86
+ def extract_requires!(yaml)
87
+ yaml.map.with_index do |a, i|
88
+ yaml.delete_at(i) if a.keys.first == 'requires'
89
+ end.compact
90
+ end
91
+ end
92
+ end
93
+ end
@@ -0,0 +1,23 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ # frozen_string_literal: true
18
+
19
+ module Elasticsearch
20
+ module Tests
21
+ VERSION = "0.1.0"
22
+ end
23
+ end
@@ -0,0 +1,18 @@
1
+ # Licensed to Elasticsearch B.V. under one or more contributor
2
+ # license agreements. See the NOTICE file distributed with
3
+ # this work for additional information regarding copyright
4
+ # ownership. Elasticsearch B.V. licenses this file to you under
5
+ # the Apache License, Version 2.0 (the "License"); you may
6
+ # not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+
18
+ Dir['./**/**.rb'].each { |f| require f }
metadata ADDED
@@ -0,0 +1,92 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: elasticsearch-test-runner
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Elastic Client Library Maintainers
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2024-06-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: elasticsearch
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: elasticsearch-serverless
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ description: A test runner for the Elasticsearch clients YAML test suite, used in
42
+ the elasticsearch and elasticsearch-serverless gems.
43
+ email:
44
+ - client-libs@elastic.co
45
+ executables: []
46
+ extensions: []
47
+ extra_rdoc_files: []
48
+ files:
49
+ - CHANGELOG.md
50
+ - CODE_OF_CONDUCT
51
+ - CONTRIBUTING.md
52
+ - LICENSE
53
+ - NOTICE
54
+ - README.md
55
+ - Rakefile
56
+ - elasticsearch-tests.gemspec
57
+ - lib/elasticsearch/tasks/download_test_suite.rake
58
+ - lib/elasticsearch/tests.rb
59
+ - lib/elasticsearch/tests/code_runner.rb
60
+ - lib/elasticsearch/tests/downloader.rb
61
+ - lib/elasticsearch/tests/errors.rb
62
+ - lib/elasticsearch/tests/printer.rb
63
+ - lib/elasticsearch/tests/test.rb
64
+ - lib/elasticsearch/tests/test_runner.rb
65
+ - lib/elasticsearch/tests/version.rb
66
+ homepage: https://www.elastic.co/guide/en/elasticsearch/client/ruby-api/current/index.html
67
+ licenses:
68
+ - Apache-2.0
69
+ metadata:
70
+ homepage_uri: https://www.elastic.co/guide/en/elasticsearch/client/ruby-api/current/index.html
71
+ changelog_uri: https://github.com/elastic/es-test-runner-ruby/blob/main/CHANGELOG.md
72
+ source_code_uri: https://github.com/elastic/es-test-runner-ruby/tree/main
73
+ post_install_message:
74
+ rdoc_options: []
75
+ require_paths:
76
+ - lib
77
+ required_ruby_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '3.0'
82
+ required_rubygems_version: !ruby/object:Gem::Requirement
83
+ requirements:
84
+ - - ">="
85
+ - !ruby/object:Gem::Version
86
+ version: '0'
87
+ requirements: []
88
+ rubygems_version: 3.5.13
89
+ signing_key:
90
+ specification_version: 4
91
+ summary: Tool to test Elasticsearch clients against the YAML clients test suite.
92
+ test_files: []