rspec_sql_matcher 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: ed99090194cf07fdc3987913d6c7ccf1df974562ab956b264485c4fba14f4b98
4
+ data.tar.gz: 674769907fe00545cfa3c7bd71c20de292201635a472fb4d2c8bbf1e5cd5edf2
5
+ SHA512:
6
+ metadata.gz: 0e3b3366ed415f5be60b01b2406ad20020a57f2f02b4265b1459cd0665ab5832bcbbbc21829cd4894afa8274298c4b1d60308f797179f7a2f88231a160c5f8ff
7
+ data.tar.gz: fc444744b9c9dcdf16d25c8dd998934b5733dea9b47c4d90ce81edd02956851a367fb6854c97bed7eb91f369b206a7a1f06f0a3b17d2993dd58dea8d147e5427
data/.editorconfig ADDED
@@ -0,0 +1,12 @@
1
+ # EditorConfig is awesome: https://EditorConfig.org
2
+
3
+ # top-most EditorConfig file
4
+ root = true
5
+
6
+ [*]
7
+ indent_style = space
8
+ indent_size = 2
9
+ end_of_line = lf
10
+ charset = utf-8
11
+ trim_trailing_whitespace = true
12
+ insert_final_newline = true
@@ -0,0 +1,72 @@
1
+ # For most projects, this workflow file will not need changing; you simply need
2
+ # to commit it to your repository.
3
+ #
4
+ # You may wish to alter this file to override the set of languages analyzed,
5
+ # or to provide custom queries or build logic.
6
+ #
7
+ # ******** NOTE ********
8
+ # We have attempted to detect the languages in your repository. Please check
9
+ # the `language` matrix defined below to confirm you have the correct set of
10
+ # supported CodeQL languages.
11
+ #
12
+ name: "CodeQL"
13
+
14
+ on:
15
+ push:
16
+ branches: [ main ]
17
+ pull_request:
18
+ # The branches below must be a subset of the branches above
19
+ branches: [ main ]
20
+ schedule:
21
+ - cron: '19 13 * * 1'
22
+
23
+ jobs:
24
+ analyze:
25
+ name: Analyze
26
+ runs-on: ubuntu-latest
27
+ permissions:
28
+ actions: read
29
+ contents: read
30
+ security-events: write
31
+
32
+ strategy:
33
+ fail-fast: false
34
+ matrix:
35
+ language: [ 'ruby' ]
36
+ # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
37
+ # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
38
+
39
+ steps:
40
+ - name: Checkout repository
41
+ uses: actions/checkout@v3
42
+
43
+ # Initializes the CodeQL tools for scanning.
44
+ - name: Initialize CodeQL
45
+ uses: github/codeql-action/init@v2
46
+ with:
47
+ languages: ${{ matrix.language }}
48
+ # If you wish to specify custom queries, you can do so here or in a config file.
49
+ # By default, queries listed here will override any specified in a config file.
50
+ # Prefix the list here with "+" to use these queries and those in the config file.
51
+
52
+ # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
53
+ # queries: security-extended,security-and-quality
54
+
55
+
56
+ # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
57
+ # If this step fails, then you should remove it and run the build manually (see below)
58
+ - name: Autobuild
59
+ uses: github/codeql-action/autobuild@v2
60
+
61
+ # ℹ️ Command-line programs to run using the OS shell.
62
+ # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
63
+
64
+ # If the Autobuild fails above, remove it and uncomment the following three lines.
65
+ # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
66
+
67
+ # - run: |
68
+ # echo "Run, Build Application using script"
69
+ # ./location_of_script_within_repo/buildscript.sh
70
+
71
+ - name: Perform CodeQL Analysis
72
+ uses: github/codeql-action/analyze@v2
@@ -0,0 +1,44 @@
1
+ name: Ruby Gem
2
+
3
+ on:
4
+ push:
5
+ tags: [ '*' ]
6
+
7
+ jobs:
8
+ build:
9
+ name: Build + Publish
10
+ runs-on: ubuntu-latest
11
+ environment: production
12
+ permissions:
13
+ contents: read
14
+ packages: write
15
+
16
+ steps:
17
+ - uses: actions/checkout@v3
18
+ - name: Set up Ruby 3.0
19
+ uses: actions/setup-ruby@v1
20
+ with:
21
+ ruby-version: 3.0.x
22
+
23
+ - name: Publish to GPR
24
+ run: |
25
+ mkdir -p $HOME/.gem
26
+ touch $HOME/.gem/credentials
27
+ chmod 0600 $HOME/.gem/credentials
28
+ printf -- "---\n:github: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials
29
+ gem build *.gemspec
30
+ gem push --KEY github --host https://rubygems.pkg.github.com/${OWNER} *.gem
31
+ env:
32
+ GEM_HOST_API_KEY: "Bearer ${{secrets.GITHUB_TOKEN}}"
33
+ OWNER: ${{ github.repository_owner }}
34
+
35
+ - name: Publish to RubyGems
36
+ run: |
37
+ mkdir -p $HOME/.gem
38
+ touch $HOME/.gem/credentials
39
+ chmod 0600 $HOME/.gem/credentials
40
+ printf -- "---\n:rubygems_api_key: ${GEM_HOST_API_KEY}\n" > $HOME/.gem/credentials
41
+ gem build *.gemspec
42
+ gem push *.gem
43
+ env:
44
+ GEM_HOST_API_KEY: "${{secrets.RUBYGEMS_AUTH_TOKEN}}"
@@ -0,0 +1,18 @@
1
+ name: Tests
2
+ on: [push, pull_request]
3
+ jobs:
4
+ test:
5
+ strategy:
6
+ fail-fast: false
7
+ matrix:
8
+ os: [ubuntu-latest, macos-latest]
9
+ # Due to https://github.com/actions/runner/issues/849, we have to use quotes for '3.0'
10
+ ruby: [2.7, '3.0', 3.1, head, truffleruby, truffleruby-head]
11
+ runs-on: ${{ matrix.os }}
12
+ steps:
13
+ - uses: actions/checkout@v2
14
+ - uses: ruby/setup-ruby@v1
15
+ with:
16
+ ruby-version: ${{ matrix.ruby }}
17
+ bundler-cache: true # runs 'bundle install' and caches installed gems automatically
18
+ - run: bundle exec rspec
data/.gitignore ADDED
@@ -0,0 +1,13 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
12
+ *.gem
13
+ /Gemfile.lock
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## [0.1.0] - 2022-09-18
2
+
3
+ - Initial release
data/Gemfile ADDED
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in rspec_sql_matcher.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.7"
13
+
14
+ gem "simplecov"
15
+
16
+ gem "activerecord", "~> 7.0", ">= 7.0.3"
17
+ gem "sqlite3"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Mònade
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # RSpec match_structure
2
+
3
+ ![Tests](https://github.com/monade/rspec_sql_matcher/actions/workflows/test.yml/badge.svg)
4
+ [![Gem Version](https://badge.fury.io/rb/rspec_sql_matcher.svg)](https://badge.fury.io/rb/rspec_sql_matcher)
5
+
6
+ A gem to match SQL queries within your RSpec tests
7
+
8
+ ## Installation
9
+
10
+ Add this line to your application's Gemfile:
11
+
12
+ ```ruby
13
+ gem 'rspec_sql_matcher'
14
+ ```
15
+
16
+ And then execute:
17
+
18
+ $ bundle install
19
+
20
+ Or install it yourself as:
21
+
22
+ $ gem install rspec_sql_matcher
23
+
24
+ ## Usage
25
+
26
+ This gem defines a couple of matchers that can help to capture queries and check if they are correctly formatted.
27
+
28
+ Moreover, with the `RSpec::SqlMatcher::Helpers` module, it defines a set of helper methods to capture data from queries executed inside theirs blocks.
29
+
30
+ ### have_run_queries
31
+ `have_run_queries` can match if a query has been run inside a block. For instance:
32
+
33
+ ```ruby
34
+ expect { YourJob.perform_now }.to have_run_queries
35
+ ```
36
+
37
+ It accepts various options:
38
+
39
+ ```ruby
40
+ expect { YourJob.perform_now }.to have_run_queries(exactly: 2)
41
+ expect { YourJob.perform_now }.to have_run_queries(min: 2, max: 5)
42
+ ```
43
+
44
+ ### match_query
45
+ `match_query` can match query content using regular expressions. For instance:
46
+
47
+ ```ruby
48
+ expect { User.very_complex_scope }.to match_query(/ GROUP BY "users"."id"/)
49
+ ```
50
+
51
+ To see all the various features please refer to the [spec file](https://github.com/monade/rspec_sql_matcher/blob/main/rspec_sql_matcher).
52
+
53
+ ## Development
54
+
55
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
56
+
57
+ 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).
58
+
59
+ ## Contributing
60
+
61
+ Bug reports and pull requests are welcome on GitHub at https://github.com/monade/rspec_sql_matcher.
62
+
63
+ ## License
64
+
65
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
66
+
67
+ About Monade
68
+ ----------------
69
+
70
+ ![monade](https://monade.io/wp-content/uploads/2021/06/monadelogo.png)
71
+
72
+ rspec_sql_matcher is maintained by [mònade srl](https://monade.io/en/home-en/).
73
+
74
+ We <3 open source software. [Contact us](https://monade.io/en/contact-us/) for your next project!
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "rspec_sql_matcher"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RSpec
4
+ module SqlMatcher
5
+ module HaveRunQueries
6
+ def self.evaluate_expectation(count, options = {})
7
+ condition = true
8
+ condition &&= count >= options[:min] if options[:min]
9
+ condition &&= count <= options[:max] if options[:max]
10
+ condition &&= count == options[:exactly] if options[:exactly]
11
+
12
+ condition
13
+ end
14
+
15
+ def self.failure_message(count, options = {})
16
+ return "Expected { } to run #{options[:exactly]} queries, but there were #{count} instead." if options[:exactly]
17
+
18
+ if options[:min] && options[:max]
19
+ return "Expected { } to run a number of query between #{options[:min]} and #{options[:max]}, but there were #{count} instead."
20
+ end
21
+
22
+ if options[:min]
23
+ return "Expected { } to run at least #{options[:min]} queries, but there were #{count} instead."
24
+ end
25
+
26
+ return "Expected { } to run at most #{options[:max]} queries, but there were #{count} instead." if options[:max]
27
+
28
+ 'Invalid expectation parameters. Please pass min, max or exactly.'
29
+ end
30
+
31
+ def self.failure_message_when_negated(_count, options = {})
32
+ return "Expected { } not to execute #{options[:exactly]} queries, but it did." if options[:exactly]
33
+ if options[:min] && options[:max]
34
+ return "Expected { } not to run a number of query between #{options[:min]} and #{options[:max]}, but it did."
35
+ end
36
+ return "Expected { } not to run at least #{options[:min]} queries, but it did." if options[:min]
37
+
38
+ return "Expected { } not to run at most #{options[:max]} queries, but it did." if options[:max]
39
+
40
+ 'Invalid expectation parameters. Please pass min, max or exactly.'
41
+ end
42
+ end
43
+ end
44
+ end
45
+
46
+ RSpec::Matchers.define :have_run_queries do |options = { min: 1 }|
47
+ match(notify_expectation_failures: true) do |block|
48
+ include RSpec::SqlMatcher
49
+ @real_count = count_queries(&block)
50
+
51
+ RSpec::SqlMatcher::HaveRunQueries.evaluate_expectation(@real_count, options)
52
+ end
53
+
54
+ supports_block_expectations
55
+
56
+ failure_message do |_|
57
+ RSpec::SqlMatcher::HaveRunQueries.failure_message(@real_count, options)
58
+ end
59
+
60
+ failure_message_when_negated do |_|
61
+ RSpec::SqlMatcher::HaveRunQueries.failure_message_when_negated(@real_count, options)
62
+ end
63
+ end
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RSpec
4
+ module SqlMatcher
5
+ module Helpers
6
+ def count_queries(&block)
7
+ count = 0
8
+ _record_sql_queries(->(_) { count += 1 }, &block)
9
+ count
10
+ end
11
+
12
+ def collect_queries(&block)
13
+ queries = []
14
+ _record_sql_queries(->(query) { queries << query }, &block)
15
+ queries
16
+ end
17
+
18
+ def log_queries(&block)
19
+ _record_sql_queries(
20
+ lambda { |data|
21
+ puts
22
+ binds = data[:binds].map { |e| "#{e.name} => #{e.value}" }.join(', ')
23
+ puts "#{data[:sql]} | #{binds}"
24
+ puts
25
+ puts
26
+ }, &block
27
+ )
28
+ end
29
+
30
+ private
31
+
32
+ def _record_sql_queries(callback)
33
+ instance = ActiveSupport::Notifications.subscribe 'sql.active_record' do |_, _, _, _, data|
34
+ callback.call(data)
35
+ end
36
+ yield
37
+ ensure
38
+ ActiveSupport::Notifications.unsubscribe(instance) if instance
39
+ end
40
+ end
41
+ end
42
+ end
@@ -0,0 +1,24 @@
1
+ # frozen_string_literal: true
2
+
3
+ RSpec::Matchers.define :match_query do |regexp|
4
+ match(notify_expectation_failures: true) do |block|
5
+ include RSpec::SqlMatcher::Helpers
6
+ @queries = collect_queries(&block).map do |data|
7
+ query = data[:sql].dup
8
+ data[:binds].each_with_index { |bind, index| query.gsub!("\$#{index + 1}", bind.value.inspect) }
9
+ query
10
+ end
11
+
12
+ @queries.any? { |query| regexp =~ query }
13
+ end
14
+
15
+ supports_block_expectations
16
+
17
+ failure_message do |_|
18
+ "Expected { } to match query with #{regexp}, but it didn't. Current queries where:\n#{@queries.join("\n")}:"
19
+ end
20
+
21
+ failure_message_when_negated do |_|
22
+ "Expected { } not to match query with #{regexp}, but it did. Current queries where:\n#{@queries.join("\n")}:"
23
+ end
24
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RSpec
4
+ module SqlMatcher
5
+ VERSION = '0.1.0'
6
+ end
7
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'sql_matcher/version'
4
+ require 'active_support'
5
+ require 'rspec/sql_matcher/helpers'
6
+ require 'rspec/sql_matcher/have_run_queries'
7
+ require 'rspec/sql_matcher/match_query'
8
+
9
+ RSpec.configure do |config|
10
+ config.include RSpec::SqlMatcher::Helpers
11
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/rspec/sql_matcher/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'rspec_sql_matcher'
7
+ spec.version = RSpec::SqlMatcher::VERSION
8
+ spec.authors = ['Mònade']
9
+ spec.email = ['hello@monade.io']
10
+
11
+ spec.summary = 'An RSpec matcher to check SQL queries'
12
+ spec.description = 'An RSpec matcher to check SQL queries'
13
+ spec.homepage = 'https://github.com/monade/rspec_sql_matcher'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = '>= 2.7'
16
+
17
+ spec.metadata['homepage_uri'] = spec.homepage
18
+ spec.metadata['source_code_uri'] = spec.homepage
19
+ spec.metadata['changelog_uri'] = 'https://github.com/monade/rspec_sql_matcher/CHANGELOG.md'
20
+
21
+ # Specify which files should be added to the gem when it is released.
22
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
23
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
24
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{\A(?:test|spec|features)/}) }
25
+ end
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{\Aexe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+
30
+ # Uncomment to register a new dependency of your gem
31
+ spec.add_dependency 'activesupport'
32
+
33
+ # For more information and examples about making a new gem, checkout our
34
+ # guide at: https://bundler.io/guides/creating_gem.html
35
+ end
metadata ADDED
@@ -0,0 +1,79 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: rspec_sql_matcher
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Mònade
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-09-18 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ description: An RSpec matcher to check SQL queries
28
+ email:
29
+ - hello@monade.io
30
+ executables: []
31
+ extensions: []
32
+ extra_rdoc_files: []
33
+ files:
34
+ - ".editorconfig"
35
+ - ".github/workflows/codeql-analysis.yml"
36
+ - ".github/workflows/gem-push.yml"
37
+ - ".github/workflows/test.yml"
38
+ - ".gitignore"
39
+ - ".rspec"
40
+ - CHANGELOG.md
41
+ - Gemfile
42
+ - LICENSE.txt
43
+ - README.md
44
+ - Rakefile
45
+ - bin/console
46
+ - bin/setup
47
+ - lib/rspec/sql_matcher.rb
48
+ - lib/rspec/sql_matcher/have_run_queries.rb
49
+ - lib/rspec/sql_matcher/helpers.rb
50
+ - lib/rspec/sql_matcher/match_query.rb
51
+ - lib/rspec/sql_matcher/version.rb
52
+ - rspec_sql_matcher.gemspec
53
+ homepage: https://github.com/monade/rspec_sql_matcher
54
+ licenses:
55
+ - MIT
56
+ metadata:
57
+ homepage_uri: https://github.com/monade/rspec_sql_matcher
58
+ source_code_uri: https://github.com/monade/rspec_sql_matcher
59
+ changelog_uri: https://github.com/monade/rspec_sql_matcher/CHANGELOG.md
60
+ post_install_message:
61
+ rdoc_options: []
62
+ require_paths:
63
+ - lib
64
+ required_ruby_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '2.7'
69
+ required_rubygems_version: !ruby/object:Gem::Requirement
70
+ requirements:
71
+ - - ">="
72
+ - !ruby/object:Gem::Version
73
+ version: '0'
74
+ requirements: []
75
+ rubygems_version: 3.2.33
76
+ signing_key:
77
+ specification_version: 4
78
+ summary: An RSpec matcher to check SQL queries
79
+ test_files: []