Skip to content

Commit

Permalink
Sets up initial gem to patch shoulda-matchers
Browse files Browse the repository at this point in the history
Since we're taking advantage of storing UUIDs in MySQL as `binary`, the shoulda-matchers has an issue when the UUID ends in an `f`.  This has lead to some flakey tests.  [We made an effort to fix this upstream](thoughtbot/shoulda-matchers#1159), which doesn't appear to be gaining traction.  This extracts the fix into a gem so we don't have to support a hard fork for this.

Pivotal Story: https://www.pivotaltracker.com/story/show/164603806
Merges #1
LGTM given by: @bsimpson
  • Loading branch information
codenamev committed Feb 6, 2020
1 parent 772ce75 commit a1cf4e1
Show file tree
Hide file tree
Showing 17 changed files with 401 additions and 1 deletion.
13 changes: 13 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/.bundle/
/.yardoc
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/**/database.yml
/spec/reports/
/tmp/
Gemfile.lock

# rspec failure tracking
.rspec_status
3 changes: 3 additions & 0 deletions .rspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--format documentation
--color
--require spec_helper
74 changes: 74 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at vstoll@doximity.com. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [https://contributor-covenant.org/version/1/4][version]

[homepage]: https://contributor-covenant.org
[version]: https://contributor-covenant.org/version/1/4/
12 changes: 12 additions & 0 deletions Gemfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
source "https://rubygems.org"

# Specify your gem's dependencies in shoulda-matchers-uuid.gemspec
gemspec

gem "activemodel", "> 5.0"
gem "activerecord", "> 4"
gem "byebug"
gem "mysql2"
gem "mysql-binuuid-rails", require: false
gem "rake", "~> 12.0"
gem "rspec", "~> 3.0"
13 changes: 13 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
Copyright 2016 Doximity, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
40 changes: 39 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,40 @@
# shoulda-matchers-uuid
The shoulda-matchers gem does not currently support MYSQL uuid columns. This extends it to allow validating uuids in models.

This is a patch to shoulda-matchers that allows the uniqueness validation matchers to work with MySQL UUIDs. The current shoulda-matchers gem incorrectly increments UUID values when they are set as `binary` types (when using the [mysql-binuuid-rails gem](https://github.com/nedap/mysql-binuuid-rails)).

We have [an existing open PR](https://github.com/thoughtbot/shoulda-matchers/pull/1159) that is likely not going to make it through.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'shoulda-matchers-uuid'
```

And then execute:

$ bundle install

Or install it yourself as:

$ gem install shoulda-matchers-uuid

## Usage

That's it! Use shoulda-matchers as usual to validate uniqueness of UUIDs.

## Development

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.

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 tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/codenamev/shoulda-matchers-uuid. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/codenamev/shoulda-matchers-uuid/blob/master/CODE_OF_CONDUCT.md).


## Code of Conduct

Everyone interacting in the Shoulda::Matchers::Uuid project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/codenamev/shoulda-matchers-uuid/blob/master/CODE_OF_CONDUCT.md).
6 changes: 6 additions & 0 deletions Rakefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require "bundler/gem_tasks"
require "rspec/core/rake_task"

RSpec::Core::RakeTask.new(:spec)

task :default => :spec
14 changes: 14 additions & 0 deletions bin/console
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/usr/bin/env ruby

require "bundler/setup"
require "shoulda/matchers/uuid"

# You can add fixtures and/or initialization code here to make experimenting
# with your gem easier. You can also use a different console, if you like.

# (If you use this, don't forget to add pry to your Gemfile!)
# require "pry"
# Pry.start

require "irb"
IRB.start(__FILE__)
8 changes: 8 additions & 0 deletions bin/setup
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
IFS=$'\n\t'
set -vx

bundle install

cp ./spec/support/database.yml.example ./spec/support/database.yml
44 changes: 44 additions & 0 deletions lib/shoulda/matchers/uuid.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# frozen_string_literal: true

require "active_support/concern"
require "shoulda/matchers"

module ShouldaMatchersMysqlUuidFix
extend ActiveSupport::Concern

included do
def next_scalar_value_for(scope, previous_value)
if uuid?(scope)
SecureRandom.uuid
elsif defined_as_enum?(scope)
available_values = available_enum_values_for(scope, previous_value)
available_values.keys.last
elsif polymorphic_type_attribute?(scope, previous_value)
Uniqueness::TestModels.create(previous_value).to_s
elsif previous_value.respond_to?(:next)
previous_value.next
elsif previous_value.respond_to?(:to_datetime)
previous_value.to_datetime.next
elsif boolean_value?(previous_value)
!previous_value
else
previous_value.to_s.next
end
end

def uuid?(scope)
[
column_for(scope),
attribute_type_for(scope)
].compact.map(&:type).include? :uuid
end

def attribute_type_for(scope)
return unless model.respond_to?(:attribute_types)

model.attribute_types[scope.to_s]
end
end
end

Shoulda::Matchers::ActiveRecord::ValidateUniquenessOfMatcher.public_send(:include, ShouldaMatchersMysqlUuidFix)
7 changes: 7 additions & 0 deletions lib/shoulda/matchers/uuid/version.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module Shoulda
module Matchers
module Uuid
VERSION = "0.1.0"
end
end
end
28 changes: 28 additions & 0 deletions shoulda-matchers-uuid.gemspec
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
require_relative 'lib/shoulda/matchers/uuid/version'

Gem::Specification.new do |spec|
spec.name = "shoulda-matchers-uuid"
spec.version = Shoulda::Matchers::Uuid::VERSION
spec.authors = ["Valentino Stoll", "Ben Simpson"]
spec.email = ["vstoll@doximity.com", "bsimpson@doximity.com"]

spec.summary = %q{Adds support for MYSQL uuids in shoulda-matchers context}
spec.description = %q{shoulda-matchers does not currently support MYSQL uuid columns. This extends it to allow validating uuids in models.}
spec.homepage = "https://github.com/doximity/shoulda-matchers-uuid"
spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")

spec.metadata["homepage_uri"] = spec.homepage
spec.metadata["source_code_uri"] = "https://github.com/doximity/shoulda-matchers-uuid"
spec.metadata["changelog_uri"] = "https://github.com/doximity/shoulda-matchers-uuid/blob/master/CHANGELOG.md"

# Specify which files should be added to the gem when it is released.
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
`git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
end
spec.bindir = "exe"
spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]

spec.add_dependency("shoulda-matchers")
end
9 changes: 9 additions & 0 deletions spec/shoulda/matchers/uuid_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# frozen_string_literal: true

require "spec_helper"

RSpec.describe Shoulda::Matchers::Uuid do
it "has a version number" do
expect(Shoulda::Matchers::Uuid::VERSION).not_to be nil
end
end
18 changes: 18 additions & 0 deletions spec/spec_helper.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# frozen_string_literal: true

require "bundler/setup"
require "rspec"
require "rspec/core/profiler"
require "shoulda/matchers/uuid"

RSpec.configure do |config|
# Enable flags like --only-failures and --next-failure
config.example_status_persistence_file_path = ".rspec_status"

# Disable RSpec exposing methods globally on `Module` and `main`
config.disable_monkey_patching!

config.expect_with :rspec do |c|
c.syntax = :expect
end
end
20 changes: 20 additions & 0 deletions spec/support/database.yml.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# MySQL. Versions 5.1.10 and up are supported.
#
# Install the MySQL driver
# gem install mysql2
#
# Ensure the MySQL gem is defined in your Gemfile
# gem 'mysql2'
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.7/en/old-client.html
#
adapter: mysql2
encoding: utf8mb4
charset: utf8mb4
collation: utf8mb4_unicode_ci
database: shoulda_matchers_uuid_test
host: localhost
port: 3306
username: root
password:
36 changes: 36 additions & 0 deletions spec/support/example_app_helpers.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# frozen_string_literal: true

require "bundler/inline"

require "active_record"
require "mysql-binuuid-rails"
require "yaml"

module ExampleAppHelpers
def setup_example_app(initial_migration_klass)
establish_database_connection
perform_migration(initial_migration_klass)
end

def teardown_example_app
ActiveRecord::Base.connection.execute("DROP DATABASE IF EXISTS #{database_configuration["database"]}")
end

def establish_database_connection
ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
ActiveRecord::Base.establish_connection(database_configuration.except("database"))
ActiveRecord::Base.connection.execute("CREATE DATABASE IF NOT EXISTS #{database_configuration["database"]}")
ActiveRecord::Base.establish_connection(database_configuration)
end

def perform_migration(migration_klass)
migration_klass.migrate(:up)
end

def database_configuration
return @database_configuration if defined? @database_configuration

db_config_file = File.open(File.expand_path(File.join(Dir.pwd, "spec", "support", "database.yml")))
@database_configuration = YAML.safe_load(db_config_file)
end
end

0 comments on commit a1cf4e1

Please sign in to comment.