Skip to content
This repository has been archived by the owner on Dec 5, 2019. It is now read-only.

Commit

Permalink
Unfreeze rubocop and address cops
Browse files Browse the repository at this point in the history
  • Loading branch information
maxlinc committed Jun 15, 2014
1 parent 7dcdfa0 commit bb36673
Show file tree
Hide file tree
Showing 33 changed files with 105 additions and 109 deletions.
2 changes: 2 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
inherit_from: .rubocop-todo.yml
# Uncomment once rubocop-rspec 1.0 is released...
# require: rubocop-rspec

AllCops:
Include:
Expand Down
4 changes: 2 additions & 2 deletions Guardfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ group :tests, halt_on_fail: true do
guard :rspec, cmd: 'bundle exec rspec' do
# Unit tests
watch(%r{^spec/unit/.+_spec\.rb$})
watch(/^lib\/(.+)\.rb$/) { |m| 'spec/unit/#{m[1]}_spec.rb' }
watch(/^lib\/(.+)\.rb$/) { |_m| 'spec/unit/#{m[1]}_spec.rb' }
watch('spec/spec_helper.rb') { 'spec/unit' }
watch('spec/unit/spec_helper.rb') { 'spec/unit' }
watch(%r{^spec/unit/data/.+\.json$}) { 'spec/unit' }
Expand All @@ -30,6 +30,6 @@ group :tests, halt_on_fail: true do
guard :cucumber, cmd: 'bundle exec cucumber', all_on_start: false do
watch(/^features\/.+\.feature$/)
watch(%r{^features/support/.+$}) { 'features' }
watch(%r{^features/step_definitions/(.+)_steps\.rb$}) { |m| Dir[File.join('**/#{m[1]}.feature')][0] || 'features' }
watch(%r{^features/step_definitions/(.+)_steps\.rb$}) { |_m| Dir[File.join('**/#{m[1]}.feature')][0] || 'features' }
end
end
3 changes: 1 addition & 2 deletions Rakefile
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ Coveralls::RakeTask.new
require 'pacto/rake_task' # FIXME: This require turns on WebMock
WebMock.allow_net_connect!

Rubocop::RakeTask.new(:rubocop) do |task|
# abort rake on failure
RuboCop::RakeTask.new(:rubocop) do |task|
task.fail_on_error = true
end

Expand Down
12 changes: 6 additions & 6 deletions features/steps/pacto_steps.rb
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
Given(/^Pacto is configured with:$/) do |string|
steps %Q{
steps %Q(
Given a file named "pacto_config.rb" with:
"""ruby
#{string}
"""
}
)
end

Given(/^I have a Rakefile$/) do
steps %Q{
steps %Q(
Given a file named "Rakefile" with:
"""ruby
require 'pacto/rake_task'
"""
}
)
end

When(/^I request "(.*?)"$/) do |url|
Expand All @@ -36,7 +36,7 @@
Given(/^an existing set of services$/) do
WebMock.stub_request(:get, 'www.example.com/service1').to_return(:body => {'thoughtworks' => 'pacto' }.to_json)
WebMock.stub_request(:post, 'www.example.com/service1').with(:body => 'thoughtworks').to_return(:body => 'pacto')
WebMock.stub_request(:get, 'www.example.com/service2').to_return(:body => {'service2' => %w{'thoughtworks', 'pacto'} }.to_json)
WebMock.stub_request(:get, 'www.example.com/service2').to_return(:body => {'service2' => %w('thoughtworks', 'pacto') }.to_json)
WebMock.stub_request(:post, 'www.example.com/service2').with(:body => 'thoughtworks').to_return(:body => 'pacto')
end

Expand All @@ -54,7 +54,7 @@
end
eof
eval(script) # rubocop:disable Eval
# It's just for testing...
# It's just for testing...

rescue SyntaxError => e
raise e
Expand Down
2 changes: 1 addition & 1 deletion features/support/env.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ class PactoWorld
PactoWorld.new
end

Around do | scenario, block |
Around do | _scenario, block |
# This is a cucumber bug (see cucumber #640)
world = self || PactoWorld.new
world.run_pacto do
Expand Down
4 changes: 2 additions & 2 deletions lib/pacto/actors/from_examples.rb
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
module Pacto
module Actors
class FirstExampleSelector
def self.select(examples, values)
def self.select(examples, _values)
Hashie::Mash.new examples.values.first
end
end
class RandomExampleSelector
def self.select(examples, values)
def self.select(examples, _values)
Hashie::Mash.new examples.values.sample
end
end
Expand Down
4 changes: 2 additions & 2 deletions lib/pacto/actors/json_generator.rb
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
module Pacto
module Actors
class JSONGenerator
def self.build_request(contract, values = {})
def self.build_request(contract, _values = {})
data = contract.request.to_hash
data['uri'] = contract.request.uri
data['body'] = JSON::Generator.generate(data['schema'])
Pacto::PactoRequest.new(data)
end

def self.build_response(contract, values = {})
def self.build_response(contract, _values = {})
data = contract.response.to_hash
data['body'] = JSON::Generator.generate(data['schema'])
Pacto::PactoResponse.new(data)
Expand Down
2 changes: 1 addition & 1 deletion lib/pacto/consumer/faraday_driver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ class FaradayDriver
def execute(req)
conn = Faraday.new(:url => req.uri.to_s) do |faraday|
faraday.response :logger if Pacto.configuration.logger.level == :debug
faraday.adapter Faraday.default_adapter
faraday.adapter Faraday.default_adapter
end

response = conn.send(req.method) do |faraday_request|
Expand Down
3 changes: 1 addition & 2 deletions lib/pacto/extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ module Extensions
HeaderKeyMap[:etag] = 'ETag'

def self.normalize_header_keys(headers)
headers.reduce({}) do |normalized, (key, value)|
headers.each_with_object({}) do |(key, value), normalized|
normalized[HeaderKeyMap[key]] = value
normalized
end
end
end
Expand Down
14 changes: 7 additions & 7 deletions lib/pacto/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def generate(pacto_request, pacto_response)
begin
contract_file = load_contract_file(pacto_request)

unless File.exists? contract_file
unless File.exist? contract_file
uri = URI(pacto_request.uri)
FileUtils.mkdir_p(File.dirname contract_file)
File.write(contract_file, save(uri, pacto_request, pacto_response))
Expand Down Expand Up @@ -65,22 +65,22 @@ def generate_request(request, response, source)
:params => request.uri.query_values,
:path => request.uri.path,
:schema => generate_schema(source, request.body)
}.delete_if { |k, v| v.nil? }
}.delete_if { |_k, v| v.nil? }
end

def generate_response(request, response, source)
{
:headers => @filters.filter_response_headers(request, response),
:status => response.status,
:schema => generate_schema(source, response.body)
}.delete_if { |k, v| v.nil? }
}.delete_if { |_k, v| v.nil? }
end

def generate_schema(source, body, generator_options = Pacto.configuration.generator_options)
if body && !body.empty?
body_schema = JSON::SchemaGenerator.generate source, body, generator_options
MultiJson.load(body_schema)
end
return if body.nil? || body.empty?

body_schema = JSON::SchemaGenerator.generate source, body, generator_options
MultiJson.load(body_schema)
end

def load_contract_file(pacto_request)
Expand Down
10 changes: 5 additions & 5 deletions lib/pacto/generator/filters.rb
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
module Pacto
class Generator
class Filters
CONNECTION_CONTROL_HEADERS = %w{
CONNECTION_CONTROL_HEADERS = %w(
Via
Server
Connection
Transfer-Encoding
Content-Length
}
)

FRESHNESS_HEADERS =
%w{
%w(
Date
Last-Modified
ETag
}
)

HEADERS_TO_FILTER = CONNECTION_CONTROL_HEADERS + FRESHNESS_HEADERS

Expand All @@ -31,7 +31,7 @@ def filter_request_headers(request, response)
end
end

def filter_response_headers(request, response)
def filter_response_headers(_request, response)
Pacto::Extensions.normalize_header_keys(response.headers).reject do |header|
(HEADERS_TO_FILTER.include? header) || (header.start_with?('X-'))
end
Expand Down
4 changes: 1 addition & 3 deletions lib/pacto/meta_schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,7 @@ def initialize(engine = JSON::Validator)

def validate(definition)
errors = engine.fully_validate(schema, definition)
unless errors.empty?
fail InvalidContract, errors
end
fail InvalidContract, errors unless errors.empty?
end
end
end
8 changes: 4 additions & 4 deletions lib/pacto/native_contract_factory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ def build_from_file(contract_path, host)

def body_to_schema(definition, section, file)
schema = definition[section].delete 'body'
if schema
Pacto::UI.deprecation "Contract format deprecation: #{section}:body will be moved to #{section}:schema (#{file})"
definition[section]['schema'] = schema
end
return nil unless schema

Pacto::UI.deprecation "Contract format deprecation: #{section}:body will be moved to #{section}:schema (#{file})"
definition[section]['schema'] = schema
end
end
end
6 changes: 3 additions & 3 deletions lib/pacto/rake_task.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def install

def validate_task
desc 'Validates all contracts in a given directory against a given host'
task :validate, :host, :dir do |t, args|
task :validate, :host, :dir do |_t, args|
if args.to_a.size < 2
fail Pacto::UI.yellow('USAGE: rake pacto:validate[<host>, <contract_dir>]')
end
Expand All @@ -32,7 +32,7 @@ def validate_task

def generate_task
desc 'Generates contracts from partial contracts'
task :generate, :input_dir, :output_dir, :host do |t, args|
task :generate, :input_dir, :output_dir, :host do |_t, args|
if args.to_a.size < 3
fail Pacto::UI.yellow('USAGE: rake pacto:generate[<request_contract_dir>, <output_dir>, <record_host>]')
end
Expand All @@ -45,7 +45,7 @@ def generate_task
# rubocop:disable MethodLength
def meta_validate
desc 'Validates a directory of contract definitions'
task :meta_validate, :dir do |t, args|
task :meta_validate, :dir do |_t, args|
if args.to_a.size < 1
fail Pacto::UI.yellow('USAGE: rake pacto:meta_validate[<contract_dir>]')
end
Expand Down
8 changes: 4 additions & 4 deletions lib/pacto/rspec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
raise 'pacto/rspec requires rspec 2 or later'
end

RSpec::Matchers.define :have_unmatched_requests do |method, uri|
RSpec::Matchers.define :have_unmatched_requests do |_method, _uri|
match do
@unmatched_validations = Pacto::ValidationRegistry.instance.unmatched_validations
!@unmatched_validations.empty?
Expand All @@ -23,7 +23,7 @@
end
end

RSpec::Matchers.define :have_failed_validations do |method, uri|
RSpec::Matchers.define :have_failed_validations do |_method, _uri|
match do
@failed_validations = Pacto::ValidationRegistry.instance.failed_validations
!@failed_validations.empty?
Expand Down Expand Up @@ -53,7 +53,7 @@
@options = options
end

def validated?(request_pattern)
def validated?(_request_pattern)
@matching_validations = Pacto::ValidationRegistry.instance.validated? @request_pattern
validated = !@matching_validations.nil?
validated && successfully? && contract_matches?
Expand Down Expand Up @@ -94,7 +94,7 @@ def contract_matches?
# buffer.puts " #{validation_result}"
# end
elsif @contract
validated_against = @matching_validations.map { |v| v.against_contract? @contract }.compact.join ','
validated_against = @matching_validations.map { |v| v.against_contract? @contract }.compact.join ','
buffer.puts " against Contract #{@contract}"
buffer.puts " but it was validated against #{validated_against}"
end
Expand Down
27 changes: 13 additions & 14 deletions lib/pacto/server/api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ module Server
class API < Goliath::API
use ::Rack::ContentLength

def initialize(opts = {})
def initialize(_opts = {})
@original_pwd = Dir.pwd
end

Expand All @@ -23,16 +23,16 @@ def options_parser(opts, options) # rubocop:disable MethodLength
options[:config] ||= File.expand_path('../config.rb', __FILE__)
options[:strip_port] ||= true

opts.on('-l', '--live', 'Send requests to live services (instead of stubs)') { |val| options[:live] = true }
opts.on('--stub', 'Stub responses based on contracts') { |val| options[:stub] = true }
opts.on('-g', '--generate', 'Generate Contracts from requests') { |val| options[:generate] = true }
opts.on('-V', '--validate', 'Validate requests/responses against Contracts') { |val| options[:validate] = true }
opts.on('-m', '--match-strict', 'Enforce strict request matching rules') { |val| options[:strict] = true }
opts.on('-l', '--live', 'Send requests to live services (instead of stubs)') { |_val| options[:live] = true }
opts.on('--stub', 'Stub responses based on contracts') { |_val| options[:stub] = true }
opts.on('-g', '--generate', 'Generate Contracts from requests') { |_val| options[:generate] = true }
opts.on('-V', '--validate', 'Validate requests/responses against Contracts') { |_val| options[:validate] = true }
opts.on('-m', '--match-strict', 'Enforce strict request matching rules') { |_val| options[:strict] = true }
opts.on('-x', '--contracts_dir DIR', 'Directory that contains the contracts to be registered') { |val| options[:directory] = File.expand_path(val, @original_pwd) }
opts.on('-H', '--host HOST', 'Host of the real service, for generating or validating live requests') { |val| options[:backend_host] = val }
opts.on('-r', '--recursive-loading', 'Load contracts from folders named after the host to be stubbed') { |val| options[:recursive_loading] = true }
opts.on('--strip-port', 'Strip the port from the request URI to build the proxied URI') { |val| options[:strip_port] = true }
opts.on('--strip-dev', 'Strip .dev from the request domain to build the proxied URI') { |val| options[:strip_dev] = true }
opts.on('-r', '--recursive-loading', 'Load contracts from folders named after the host to be stubbed') { |_val| options[:recursive_loading] = true }
opts.on('--strip-port', 'Strip the port from the request URI to build the proxied URI') { |_val| options[:strip_port] = true }
opts.on('--strip-dev', 'Strip .dev from the request domain to build the proxied URI') { |_val| options[:strip_dev] = true }
end

def response(env)
Expand Down Expand Up @@ -60,15 +60,15 @@ def prepare_em_request(env)
:head => filter_request_headers(env),
:query => env['QUERY_STRING'],
:body => env['async-body']
}.delete_if { | k, v | v.nil? }
}.delete_if { | _k, v | v.nil? }
EventMachine::HttpRequest.new(uri).send(em_request_method, em_request_options)
end

def process_pacto_response(resp, env)
fail resp.error if resp.error

code = resp.response_header.http_status
safe_response_headers = normalize_headers(resp.response_header).reject { |k, v| %w{connection content-encoding content-length transfer-encoding}.include? k.downcase }
safe_response_headers = normalize_headers(resp.response_header).reject { |k, _v| %w(connection content-encoding content-length transfer-encoding).include? k.downcase }
body = proxy_rewrite(resp.response)

env.logger.debug "response headers: #{safe_response_headers}"
Expand Down Expand Up @@ -96,7 +96,7 @@ def determine_proxy_uri(env)

def filter_request_headers(env)
headers = env['client-headers']
safe_headers = headers.reject { |k, v| %w{host content-length transfer-encoding}.include? k.downcase }
safe_headers = headers.reject { |k, _v| %w(host content-length transfer-encoding).include? k.downcase }
env.logger.debug "filtered headers: #{safe_headers}"
safe_headers
end
Expand All @@ -106,13 +106,12 @@ def port
end

def normalize_headers(headers)
headers.reduce({}) do |res, elem|
headers.each_with_object({}) do |elem, res|
key = elem.first.dup
value = elem.last
key.gsub!('_', '-')
key = key.split('-').map { |w| w.capitalize }.join '-'
res[key] = value
res
end
end

Expand Down
2 changes: 1 addition & 1 deletion lib/pacto/server/config.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,6 @@ def prepare_contracts(contracts)
Pacto.validate! if options[:validate]

if options[:live]
# WebMock.reset!
# WebMock.reset!
WebMock.allow_net_connect!
end
Loading

0 comments on commit bb36673

Please sign in to comment.