repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
twei55/simple-bookshelf
db/migrate/20120323161737_create_books_tags_join_table.rb
<filename>db/migrate/20120323161737_create_books_tags_join_table.rb class CreateBooksTagsJoinTable < ActiveRecord::Migration def up create_table :books_nested_tags, :id => false, :force => true do |t| t.column :book_id, :integer t.column :nested_tag_id, :integer t.timestamps end end def down drop_table :books_nested_tags end end
twei55/simple-bookshelf
app/models/book_author.rb
<gh_stars>0 class BookAuthor < ActiveRecord::Base belongs_to :book belongs_to :author end
twei55/simple-bookshelf
db/migrate/20120622213029_create_entries.rb
class CreateEntries < ActiveRecord::Migration def up create_table :entries, :force => true do |t| t.integer :book_id t.integer :group_id t.timestamps end end def down drop_table :entries end end
twei55/simple-bookshelf
spec/controllers/books_controller_spec.rb
<gh_stars>0 require 'spec_helper' describe BooksController do context "unauthorized" do context "GET index" do it "redirects to login page" do get :index response.should be_redirect end end end context "admin" do login_admin context "GET index" do it "renders index page" do get :index response.should be_success response.should render_template('index') end end context "GET new" do it "renders index page" do get :new response.should be_success response.should render_template('new') end end end context "user" do login_user context "GET index" do it "renders index page" do get :index response.should be_success response.should render_template('index') end end context "GET new" do it "renders index page" do get :new response.should be_redirect end end end end
twei55/simple-bookshelf
spec/factories/authors.rb
# encoding: utf-8 # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :author do first_name "Vorname" last_name "Nachname" factory :rowohlt do first_name "Harry" last_name "Rowohlt" end factory :timm do first_name "Uwe" last_name "Timm" end factory :haruki do first_name "Haruki" last_name "Murakami" end factory :gibson do first_name "William" last_name "Gibson" end factory :meier do first_name "Clemens" last_name "Meier" end end end
twei55/simple-bookshelf
app/models/group.rb
class Group < ActiveRecord::Base has_many :users has_one :admin has_many :entries has_many :books, :through => :entries validates_presence_of :name end
twei55/simple-bookshelf
spec/requests/query_books_spec.rb
# encoding: utf-8 require 'spec_helper' describe "query" do let(:admin) { FactoryGirl.create(:admin, :group => Group.first) } let(:user) { FactoryGirl.create(:user, :group => Group.first) } before(:each) do visit new_user_session_path fill_in("user_email", :with => admin.email) fill_in("user_password", :with => <PASSWORD>) click_button("Einloggen") end it "performs some queries" do fill_in("query", :with => "<NAME>") click_button("Suche") page.should have_content("Die Erfindung der Currywurst") page.should have_content("Am Beispiel meines Bruders") page.should_not have_content("<NAME>") fill_in("query", :with => "Erfindung") click_button("Suche") page.should have_content("Die Erfindung der Currywurst") page.should have_content("Die Erfindung der Bratwurst") page.should_not have_content("Am Beispiel meines Bruders") end end
twei55/simple-bookshelf
spec/controllers/nested_tags_controller_spec.rb
<reponame>twei55/simple-bookshelf require 'spec_helper' describe NestedTagsController do end
twei55/simple-bookshelf
spec/models/user_spec.rb
require 'spec_helper' describe User do describe '.add_to_group' do let(:group) {FactoryGirl.create(:group1)} let(:user) {FactoryGirl.build(:user)} context "group name given" do it "creates a new group and adds user to it" do params = {"group" => {"id" => "", "name" => "Neue Gruppe"}} user.add_to_group(params["group"]) user.group.should_not be_nil user.group.name.should == "Neue Gruppe" user.admin?.should be_true end end context "group id given" do it "adds user to an existing group" do params = {"group" => {"id" => group.id, "name" => ""}} user.add_to_group(params["group"]) user.group.should == group user.group.name.should == "Gruppe 1" user.admin?.should be_false end end context "group name and id given" do it "does not add user to a group" do params = {"group" => {"id" => group.id, "name" => "Neue Gruppe"}} user.add_to_group(params["group"]) user.valid?.should be_false end end end end
twei55/simple-bookshelf
db/migrate/20120623134237_drop_admins_table.rb
class DropAdminsTable < ActiveRecord::Migration def up drop_table :admins end def down end end
twei55/simple-bookshelf
spec/models/author_spec.rb
<filename>spec/models/author_spec.rb require 'spec_helper' describe Author do describe "#full_name" do end describe ".find_or_create" do end end
twei55/simple-bookshelf
spec/factories/nested_tags.rb
<reponame>twei55/simple-bookshelf # encoding: utf-8 # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :tag1, :class => NestedTag do name "Alleinerziehende" parent_id 0 end factory :tag2, :class => NestedTag do name "Bildung" parent_id 0 end factory :tag3, :class => NestedTag do name "Unterhaltsrecht" parent_id 0 end factory :tag4, :class => NestedTag do name "Erziehung" parent_id 0 end factory :tag5, :class => NestedTag do name "Science" parent_id 0 end factory :tag6, :class => NestedTag do name "Abbildung" end factory :tag7, :class => NestedTag do name "Ausbildung" end factory :tag8, :class => NestedTag do name "Vorbildung" end end
twei55/simple-bookshelf
app/models/nested_tag.rb
class NestedTag < ActiveRecord::Base acts_as_tree :order => "name" ################################ ### ActiveRecord Associations ## ################################ has_and_belongs_to_many :books, :join_table => "books_nested_tags" validates_presence_of :name scope :root, :conditions => ["parent_id = ?",0], :order => "LOWER(name) ASC" scope :sorted, :order => "LOWER(name) ASC" scope :in_use, :select => "DISTINCT nested_tags.*", :joins => :books, :order => "name ASC" end
twei55/simple-bookshelf
spec/factories/users.rb
# encoding: utf-8 # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :user do sequence(:email) {|n| "<EMAIL>" } password "<PASSWORD>" password_confirmation "<PASSWORD>" confirmed_at Time.now end factory :admin, :class => User do sequence(:email) {|n| "<EMAIL>" } password "<PASSWORD>" password_confirmation "<PASSWORD>" confirmed_at Time.now admin true end end
twei55/simple-bookshelf
spec/requests/keywords_spec.rb
# encoding: utf-8 require 'spec_helper' describe "create, update, delete keywords" do let(:admin) { FactoryGirl.create(:admin, :group => Group.first) } let(:user) { FactoryGirl.create(:user, :group => Group.first) } before(:each) do visit new_user_session_path fill_in("user_email", :with => admin.email) fill_in("user_password", :with => <PASSWORD>) click_button("Einloggen") end it "creates a new keyword" do visit keywords_path within("div#new-keyword-form") do fill_in("nested_tag_name", :with => "Exklusion") end click_button("Hinzufügen") find("#nested_tag_parent_id").has_text?("Exklusion").should be_true within("div#update-keyword-form") do find("#book_nested_tag_ids").has_text?("Exklusion").should be_true end end it "updates an existing keyword" do visit keywords_path within("div#update-keyword-form") do select('Exklusion', :from => "book_nested_tag_ids") fill_in("nested_tag_name", :with => 'Ausschluß') end click_button("Aktualisieren") find("#nested_tag_parent_id").has_text?("Ausschluß").should be_true within("div#update-keyword-form") do find("#book_nested_tag_ids").has_text?("Ausschluß").should be_true end end it "deletes an existing format" do visit keywords_path within("div#delete-keyword-form") do select('Ausschluß', :from => "book_nested_tag_ids") click_button("Löschen") end find("#nested_tag_parent_id").has_text?("Ausschluß").should be_false within("div#update-keyword-form") do find("#book_nested_tag_ids").has_text?("Ausschluß").should be_false end end end
twei55/simple-bookshelf
db/migrate/20120623134029_add_admin_flag_to_users.rb
class AddAdminFlagToUsers < ActiveRecord::Migration def up add_column :users, :admin, :boolean, :default => false end def down remove_column :users, :admin end end
twei55/simple-bookshelf
spec/spec_helper.rb
# This file is copied to spec/ when you run 'rails generate rspec:install' ENV["RAILS_ENV"] ||= 'test' require File.expand_path("../../config/environment", __FILE__) require 'rspec/rails' require 'rspec/autorun' require 'capybara/rspec' require 'thinking_sphinx/test' # Requires supporting ruby files with custom matchers and macros, etc, # in spec/support/ and its subdirectories. Dir[Rails.root.join("spec/support/**/*.rb")].each {|f| require f} RSpec.configure do |config| # ## Mock Framework # # If you prefer to use mocha, flexmock or RR, uncomment the appropriate line: # # config.mock_with :mocha # config.mock_with :flexmock # config.mock_with :rr # Remove this line if you're not using ActiveRecord or ActiveRecord fixtures config.fixture_path = "#{::Rails.root}/spec/fixtures" # If you're not using ActiveRecord, or you'd prefer not to run each of your # examples within a transaction, remove the following line or assign false # instead of true. config.use_transactional_fixtures = false # If true, the base class of anonymous controllers will be inferred # automatically. This will be the default behavior in future versions of # rspec-rails. config.infer_base_class_for_anonymous_controllers = false # Database Cleaner settings # https://github.com/bmabey/database_cleaner config.before(:suite) do DatabaseCleaner.strategy = :truncation end config.before(:all) do DatabaseCleaner.start ThinkingSphinx::Test.start create_dummy_data ThinkingSphinx::Test.index end config.after(:all) do DatabaseCleaner.clean end config.include Devise::TestHelpers, :type => :controller config.extend ControllerMacros, :type => :controller end def create_dummy_data # Create some authors gibson = FactoryGirl.create(:gibson) timm = FactoryGirl.create(:timm) rowohlt = FactoryGirl.create(:rowohlt) haruki = FactoryGirl.create(:haruki) meier = FactoryGirl.create(:meier) # Create some formats dossier = FactoryGirl.create(:dossier) studie = FactoryGirl.create(:studie) gesetz = FactoryGirl.create(:gesetz) roman = FactoryGirl.create(:roman) # Create some tags tag1 = FactoryGirl.create(:tag1) tag3 = FactoryGirl.create(:tag3) tag4 = FactoryGirl.create(:tag4) tag5 = FactoryGirl.create(:tag5) tag6 = FactoryGirl.create(:tag6) tag7 = FactoryGirl.create(:tag7) tag8 = FactoryGirl.create(:tag8) tag2 = FactoryGirl.create(:tag2, :children => [tag6, tag7, tag8]) # Create a group group1 = FactoryGirl.create(:group1) group2 = FactoryGirl.create(:group2) # Create some books FactoryGirl.create(:book0, :authors => [gibson], :formats => [roman], :nested_tags => [tag1], :groups => [group1]) FactoryGirl.create(:book1, :authors => [gibson], :formats => [roman], :nested_tags => [tag1, tag2], :groups => [group1]) FactoryGirl.create(:book2, :authors => [timm], :formats => [studie], :nested_tags => [tag2], :groups => [group1]) FactoryGirl.create(:book3, :authors => [timm], :formats => [studie], :nested_tags => [tag3], :groups => [group1]) FactoryGirl.create(:book4, :authors => [rowohlt], :formats => [dossier], :nested_tags => [tag4], :groups => [group1]) FactoryGirl.create(:book5, :authors => [haruki], :formats => [dossier], :nested_tags => [tag1, tag5], :groups => [group1]) FactoryGirl.create(:book6, :authors => [haruki], :formats => [gesetz], :nested_tags => [tag5], :groups => [group1]) FactoryGirl.create(:book7, :authors => [haruki], :formats => [gesetz], :nested_tags => [tag3], :groups => [group1]) FactoryGirl.create(:book8, :authors => [meier], :formats => [roman], :nested_tags => [tag3], :groups => [group1]) FactoryGirl.create(:book9, :authors => [meier], :formats => [roman], :nested_tags => [tag3], :groups => [group1]) end
twei55/simple-bookshelf
spec/factories/formats.rb
<filename>spec/factories/formats.rb # encoding: utf-8 # Read about factories at https://github.com/thoughtbot/factory_girl FactoryGirl.define do factory :dossier, :class => Format do name "Dossier" end factory :studie, :class => Format do name "Studie" end factory :gesetz, :class => Format do name "Gesetzentwurf" end factory :roman, :class => Format do name "Roman" end end
twei55/simple-bookshelf
spec/models/nested_tag_spec.rb
<reponame>twei55/simple-bookshelf<filename>spec/models/nested_tag_spec.rb<gh_stars>0 require 'spec_helper' describe NestedTag do end
twei55/simple-bookshelf
app/models/book.rb
<reponame>twei55/simple-bookshelf # encoding: utf-8 class Book < ActiveRecord::Base ################################ ### ActiveRecord Associations ## ################################ has_many :book_authors has_many :authors, :through => :book_authors has_many :entries has_many :groups, :through => :entries accepts_nested_attributes_for :authors, :reject_if => :has_no_author_or_publisher?, :allow_destroy => true has_and_belongs_to_many :nested_tags, :join_table => "books_nested_tags" has_and_belongs_to_many :formats ############### # Validations ############### validates_presence_of :title, :message => I18n.t("sb.book.validations.title_missing") validates_presence_of :year, :message => I18n.t("sb.book.validations.year_missing") validates_presence_of :publisher, :message => I18n.t("sb.book.validations.publisher_missing") validates_presence_of :authors, :message => I18n.t("sb.book.validations.author_missing") validates_associated :authors, :message => I18n.t("sb.book.validations.author_missing") # validates_attachment_content_type :document, :content_type => ['application/pdf'], # :allow_blank => true, :message => I18n.t("sb.book.validations.attachment_content_type") ############### # Scopes ############### default_scope :order => "title ASC" # Attention # Works only with tables of type = MyISAM scope :similar_title, lambda {|terms| terms = terms.split(" ").join(" +").insert(0,"+") { :select => "id,title", :conditions => ["MATCH (title) AGAINST (? IN BOOLEAN MODE)",terms] } } ############## # Paperclip ############## has_attached_file :document, :url => "/system/books/documents/:id/original/:basename.:extension", :path => ":rails_root/public/system/books/documents/:id/original/:basename.:extension" ############## # Thinking Sphinx ############## self.per_page = 20 define_index do indexes title, :sortable => true indexes publisher, :sortable => true indexes authors(:first_name), :as => :author_first_name, :sortable => true indexes authors(:last_name), :as => :author_last_name, :sortable => true indexes authors(:full_name), :as => :author_full_name indexes authors(:full_name_reversed), :as => :author_full_name_reversed, :sortable => true indexes formats.id, :as => :format_id indexes nested_tags.id, :as => :tag_id indexes groups.id, :as => :group_id has year set_property :delta => true end # # Copy publisher name to author last name # and check if attribute is blank def has_no_author_or_publisher?(author) author["last_name"] = self.publisher if self.publisher_is_author author["last_name"].blank? end class << self def add_conditions(params, user) conditions = {} conditions[:tag_id] = params[:book][:tag] if params[:book] && params[:book][:tag].present? conditions[:format_id] = params[:book][:format] if params[:book] && params[:book][:format].present? conditions[:group_id] = user.group_id return conditions end def build_query_string(params) return "" if params[:query] && params[:query].strip.eql?("") fields = [] if params[:choices] && Book.is_selected?(params[:choices][:author]) fields = ["@author_first_name", "@author_last_name", "@author_full_name", "@author_full_name_reversed"] end fields << "@title" if params[:choices] && Book.is_selected?(params[:choices][:title]) fields << "@publisher" if params[:choices] && Book.is_selected?(params[:choices][:publisher]) fields.present? ? fields.join(" \"#{params[:query]}\" | ") + " \"#{params[:query]}\"" : params[:query] end def filter(params, user) result = Book.search( build_query_string(params), :page => params[:page] || 1, :per_page => 20, :sort_mode => params[:order] ? params[:order].to_sym : :asc, :order => params[:sort] ? params[:sort].to_sym : :author_last_name, :match_mode => :extended, :conditions => add_conditions(params, user) ) return result end def is_selected?(choice) choice && choice.eql?("1") end end end
twei55/simple-bookshelf
spec/models/book_author_spec.rb
<reponame>twei55/simple-bookshelf require 'spec_helper' describe BookAuthor do end
twei55/simple-bookshelf
app/models/format.rb
<reponame>twei55/simple-bookshelf class Format < ActiveRecord::Base ################################ ### ActiveRecord Associations ## ################################ has_and_belongs_to_many :books attr_accessible :name validates_presence_of :name end
twei55/simple-bookshelf
app/controllers/formats_controller.rb
<reponame>twei55/simple-bookshelf<gh_stars>0 # encoding: utf-8 class FormatsController < ApplicationController before_filter :authenticate_admin def index @format = Format.new end def create @format = Format.new(params[:format]) if Format.find_by_name(params[:format][:name]).nil? if (!@format.nil? && @format.save) flash[:notice] = I18n.t("sb.flash.notices.create_format_success") else flash[:error] = I18n.t("sb.flash.errors.create_format_error") end redirect_to formats_path end def update begin @format = Format.find(params[:format][:id]) @format.update_attributes(params[:format]) flash[:notice] = I18n.t("sb.flash.notices.update_format_success") redirect_to formats_path rescue ActiveRecord::RecordNotFound flash[:error] = I18n.t("sb.flash.errors.update_format_error") redirect_to formats_path end end def destroy begin @format = Format.find(params[:format][:id]) @format.destroy flash[:notice] = I18n.t("sb.flash.notices.delete_format_success") redirect_to formats_path rescue ActiveRecord::RecordNotFound flash[:error] = I18n.t("sb.flash.errors.delete_format_error") redirect_to formats_path end end end
lfu/ansible_tower_client_ruby
spec/api_spec.rb
<reponame>lfu/ansible_tower_client_ruby describe AnsibleTowerClient::Api do let(:faraday_connection) { AnsibleTowerClient::MockApi.new(:api_version => api_version) } let(:api_version) { 1 } subject { described_class.new(faraday_connection, api_version) } it "#instance returns an existing instance" do expect(subject.instance).to be(faraday_connection) end it "#hosts returns a collection" do expect(subject.hosts).to be_kind_of(AnsibleTowerClient::Collection) end context "helper methods" do context "requiring a connection" do describe "config" do it "#config returns the server config" do json = subject.config expect(json['eula']).to eq "text" expect(json['license_info']).to be_a Hash end it "#version returns the ansible tower version" do expect(subject.version).to eq "3.0.1" end end describe "#verify_credentials" do let(:get) { instance_double("Faraday::Result", :body => credentials_body) } it "returns the username" do expect(subject.verify_credentials).to eq "admin" end end describe "#method_missing" do let(:plain_response_body) { "some response" } let(:json_response_body) { { "some_key" => "some_value" } } let(:path_to_resource) { 'some/path' } it "logs method call with formatted JSON response body" do expect(subject).to receive(:build_path_to_resource).and_return(path_to_resource) connection_response = instance_double("Faraday::Response", :body => json_response_body.to_json) expect(faraday_connection).to receive(:get).and_return(connection_response) expect(AnsibleTowerClient.logger).to receive(:debug) do |&block| expect(block.call).to eq("AnsibleTowerClient::Api Sending <get> with <#{[path_to_resource].inspect}>") end expect(AnsibleTowerClient.logger).to receive(:debug) do |&block| expect(block.call).to eq("AnsibleTowerClient::Api Response:\n#{json_response_body.pretty_inspect}") end subject.get end it "logs method call with plain text response body" do expect(subject).to receive(:build_path_to_resource).and_return(path_to_resource) connection_response = instance_double("Faraday::Response", :body => plain_response_body) expect(faraday_connection).to receive(:get).and_return(connection_response) expect(AnsibleTowerClient.logger).to receive(:debug) do |&block| expect(block.call).to eq("AnsibleTowerClient::Api Sending <get> with <#{[path_to_resource].inspect}>") end expect(AnsibleTowerClient.logger).to receive(:debug) do |&block| expect(block.call).to eq("AnsibleTowerClient::Api Response:\n#{plain_response_body}") end subject.get end it "raises actual error, not NameError" do error = 'some error' expect(faraday_connection).to receive(:get).and_raise(error) expect { subject.get }.to raise_error(error) end end describe "#api_version" do describe "1" do let(:api_version) { 1 } it "returns api version that of instance" do expect(subject.api_version).to eq(1) end end describe "2" do let(:api_version) { 2 } it "returns api version that of instance" do expect(subject.api_version).to eq(2) end end end end end context "private methods" do context "#build_path_to_resource" do { "/" => { "/api/v1/hosts" => "/api/v1/hosts", "/api/v1/hosts/" => "/api/v1/hosts/", "/api/v1/hosts/5" => "/api/v1/hosts/5", "/api/v1/hosts/5/" => "/api/v1/hosts/5/", "/api/v1/hosts?page=2" => "/api/v1/hosts?page=2", "/api/v1/hosts/?page=2" => "/api/v1/hosts/?page=2", }, "/api/v1" => { "/api/v1/hosts" => "/api/v1/hosts", "/api/v1/hosts/" => "/api/v1/hosts/", "/api/v1/hosts/5" => "/api/v1/hosts/5", "/api/v1/hosts/5/" => "/api/v1/hosts/5/", "/api/v1/hosts?page=2" => "/api/v1/hosts?page=2", "/api/v1/hosts/?page=2" => "/api/v1/hosts/?page=2", }, "/api/v2" => { "/api/v1/hosts" => "/api/v2/hosts", "/api/v1/hosts/" => "/api/v2/hosts/", "/api/v1/hosts/5" => "/api/v2/hosts/5", "/api/v1/hosts/5/" => "/api/v2/hosts/5/", "/api/v1/hosts?page=2" => "/api/v2/hosts?page=2", "/api/v1/hosts/?page=2" => "/api/v2/hosts/?page=2", }, "/tower" => { "/api/v1/hosts" => "/tower/hosts", "/api/v1/hosts/" => "/tower/hosts/", "/api/v1/hosts/5" => "/tower/hosts/5", "/api/v1/hosts/5/" => "/tower/hosts/5/", "/api/v1/hosts?page=2" => "/tower/hosts?page=2", "/api/v1/hosts/?page=2" => "/tower/hosts/?page=2", }, "/nested/more/than/necessary" => { "/api/v1/hosts" => "/nested/more/than/necessary/hosts", "/api/v1/hosts/" => "/nested/more/than/necessary/hosts/", "/api/v1/hosts/5" => "/nested/more/than/necessary/hosts/5", "/api/v1/hosts/5/" => "/nested/more/than/necessary/hosts/5/", "/api/v1/hosts?page=2" => "/nested/more/than/necessary/hosts?page=2", "/api/v1/hosts/?page=2" => "/nested/more/than/necessary/hosts/?page=2", }, }.each do |path, matrix| it "connection path #{path}" do url = "https://server.example.com:8080#{path}" connection = AnsibleTowerClient::Connection.new(:username => "user", :password => "<PASSWORD>", :base_url => url) api = connection.api(:version => api_version) matrix.each do |default_path, corrected_path| expect(api.send(:build_path_to_resource, default_path)).to eq(corrected_path) end end end end end end
lfu/ansible_tower_client_ruby
spec/support/mock_api.rb
module AnsibleTowerClient class MockApi class Response attr_reader :body, :api_version def initialize(body) @body = body end end def initialize(version = nil, api_version: 2) @awx_version = version @api_version = api_version end def get(path, get_options = nil) suffix = path.split("api/v1/").last case suffix when "ad_hoc_commands" wrap_response(AdHocCommand.response) when "config" wrap_response(Config.response(@awx_version)) when "credentials" if api_version?(2) wrap_response(CredentialV2.response) else wrap_response(Credential.response) end when "credential_types" wrap_response(CredentialTypeV2.response) when "groups" wrap_response(Group.response) when "hosts" wrap_response(Host.response) when "inventories" wrap_response(Inventory.response) when "inventory_sources" wrap_response(InventorySource.response) when "jobs" wrap_response(Job.response) when "job_templates" wrap_response(JobTemplate.response) when "organizations" wrap_response(Organization.response) when "projects" wrap_response(Project.response) when "me" wrap_response(Me.response) when "workflow_jobs" wrap_response(WorkflowJob.response) when "workflow_job_nodes" wrap_response(WorkflowJobNode.response) when "workflow_job_template_nodes" wrap_response(WorkflowJobTemplateNode.response) when "workflow_job_templates" wrap_response(WorkflowJobTemplate.response) end end def wrap_response(data) AnsibleTowerClient::MockApi::Response.new(data) end def api_version?(desired) @api_version == desired end end end
lfu/ansible_tower_client_ruby
spec/job_template_v2_spec.rb
describe AnsibleTowerClient::JobTemplateV2 do let(:url) { "example.com/api/v1/job_templates" } let(:api) { AnsibleTowerClient::Api.new(connection, 1) } let(:connection) { AnsibleTowerClient::MockApi.new("2.1") } let(:raw_instance) { build(:response_instance, :job_template, :klass => described_class.base_class) } let(:raw_instance_no_extra_vars) { build(:response_instance, :job_template, :klass => described_class.base_class, :extra_vars => '') } let(:raw_instance_no_survey) { build(:response_instance, :job_template, :klass => described_class.base_class, :related => {}) } include_examples "Api Methods" include_examples "Crud Methods" include_examples "JobTemplate#extra_vars_hash" include_examples "JobTemplate#initialize" include_examples "JobTemplate#survey_spec" include_examples "JobTemplate#survey_spec_hash" describe '#launch' do let(:json) { {'extra_vars' => "{\"instance_ids\":[\"i-999c\"],\"state\":\"absent\",\"subnet_id\":\"subnet-887\"}"} } let(:post_result_body) { {:job => 1} } let(:patch_result_body) { {} } let(:config) { {"version" => "2.1.1"} } it "runs an existing job template" do expect_any_instance_of(AnsibleTowerClient::Collection).to receive(:find).with(post_result_body[:job]) expect(api).to receive(:post).and_return(instance_double("Faraday::Response", :body => post_result_body.to_json)) expect(api).to receive(:patch).twice.and_return(instance_double("Faraday::Response", :body => post_result_body.to_json)) described_class.new(api, raw_instance).launch(json) end it "handles limit when passed in" do expect(connection).to receive(:patch).twice.and_return(instance_double("Faraday::Response", :body => patch_result_body.to_json)) described_class.new(api, raw_instance).send(:with_temporary_changes, 'test') { '' } end it "handles limit when passed in with a key as a symbol" do vars = {:extra_vars => {:blah => :nah}.to_json, :limit => 'test_string'} expect_job_template_responses described_class.new(api, raw_instance).launch(vars) end it "handles limit when passed in with a key as a string" do vars = {:extra_vars => {:blah => :nah}.to_json, 'limit' => 'test_string'} expect_job_template_responses described_class.new(api, raw_instance).launch(vars) end def expect_job_template_responses expect_any_instance_of(AnsibleTowerClient::Collection).to receive(:find).with(post_result_body[:job]) expect(api).to receive(:post).and_return(instance_double("Faraday::Response", :body => post_result_body.to_json)) dummy = Class.new do def url(_) end def headers {} end def body=(_) end end.new expect(dummy).to receive(:body=).with("{ \"limit\": \"test_string\" }") expect(dummy).to receive(:body=).with("{ \"limit\": \"\" }") expect(connection).to receive(:patch).twice.and_yield(dummy).and_return(instance_double("Faraday::Response", :body => patch_result_body.to_json)) end end end
lfu/ansible_tower_client_ruby
lib/ansible_tower_client/base_models/workflow_job_node.rb
<reponame>lfu/ansible_tower_client_ruby module AnsibleTowerClient class WorkflowJobNode < BaseModel def workflow_job api.workflow_jobs.find(workflow_job_id) end def job job_id.nil? ? nil : api.jobs.find(job_id) end end end
lfu/ansible_tower_client_ruby
spec/support/mock_api/v2/credential.rb
module AnsibleTowerClient class MockApi module CredentialV2 def self.collection [ { :id => 2, :type => "credential", :url => "/api/v2/credentials/2/", :related => { :created_by => "/api/v2/users/1/", :modified_by => "/api/v2/users/1/", :organization => "/api/v2/organizations/2/", :owner_users => "/api/v2/credentials/2/owner_users/", :object_roles => "/api/v2/credentials/2/object_roles/", :owner_teams => "/api/v2/credentials/2/owner_teams/", :copy => "/api/v2/credentials/2/copy/", :activity_stream => "/api/v2/credentials/2/activity_stream/", :access_list => "/api/v2/credentials/2/access_list/", :credential_type => "/api/v2/credential_types/1/" }, :summary_fields => { :host => {}, :project => {}, :organization => { :id => 2, :name => "ManageIQ", :description => "ManageIQ Default Organization" }, :created_by => { :id => 1, :username => "admin", :first_name => "", :last_name => "" }, :modified_by => { :id => 1, :username => "admin", :first_name => "", :last_name => "" }, :object_roles => { :admin_role => { :id => 35, :description => "Can manage all aspects of the credential", :name => "Admin" }, :use_role => { :id => 37, :description => "Can use the credential in a job template", :name => "Use" }, :read_role => { :id => 36, :description => "May view settings for the credential", :name => "Read" } }, :user_capabilities => { :edit => true, :copy => true, :delete => true }, :owners => [ { :url => "/api/v2/organizations/2/", :description => "ManageIQ Default Organization", :type => "organization", :id => 2, :name => "ManageIQ" } ] }, :created => "2018-06-11T07:47:45.503385Z", :modified => "2018-06-11T07:47:45.567457Z", :name => "ManageIQ Default Credential", :description => "", :organization => 2, :credential_type => 1, :inputs => {} }, { :id => 3, :type => "credential", :url => "/api/v2/credentials/3/", :related => { :created_by => "/api/v2/users/1/", :modified_by => "/api/v2/users/1/", :owner_users => "/api/v2/credentials/3/owner_users/", :object_roles => "/api/v2/credentials/3/object_roles/", :owner_teams => "/api/v2/credentials/3/owner_teams/", :copy => "/api/v2/credentials/3/copy/", :activity_stream => "/api/v2/credentials/3/activity_stream/", :access_list => "/api/v2/credentials/3/access_list/", :credential_type => "/api/v2/credential_types/16/", :user => "/api/v2/users/1/" }, :summary_fields => { :host => {}, :project => {}, :created_by => { :id => 1, :username => "admin", :first_name => "", :last_name => "" }, :modified_by => { :id => 1, :username => "admin", :first_name => "", :last_name => "" }, :object_roles => { :admin_role => { :id => 43, :description => "Can manage all aspects of the credential", :name => "Admin" }, :use_role => { :id => 45, :description => "Can use the credential in a job template", :name => "Use" }, :read_role => { :id => 44, :description => "May view settings for the credential", :name => "Read" } }, :user_capabilities => { :edit => true, :copy => true, :delete => true }, :owners => [ { :url => "/api/v2/users/1/", :description => " ", :type => "user", :id => 1, :name => "admin" } ] }, :created => "2018-06-11T10:56:56.150390Z", :modified => "2018-06-11T10:56:56.247713Z", :name => "NuageGUI", :description => "", :organization => nil, :credential_type => 16, :inputs => { :nuage_username => "myusername", :nuage_password => <PASSWORD>$", :nuage_version => "v5_0", :nuage_enterprise => "myenterprise", :nuage_url => "myurl.com" } } ] end def self.response { "count" => collection.length, "next" => nil, "previous" => nil, "results" => collection }.to_json end end end end
lfu/ansible_tower_client_ruby
spec/project_spec.rb
<gh_stars>0 describe AnsibleTowerClient::Project do let(:url) { "example.com/api/v1/projects" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :project, :klass => described_class) } include_examples "Api Methods" include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.projects.all.first expect(obj).to be_a(described_class) expect(obj.id).to be_a(Integer) expect(obj.url).to be_a(String) expect(obj.organization_id).to be_a(Integer) expect(obj.description).to be_a(String) expect(obj.name).to be_a(String) end describe '#can_update?' do let(:can_update_true) { {'can_update' => true} } let(:can_update_false) { {'can_update' => false} } it 'returns true' do expect(api).to receive(:get).and_return(instance_double("Faraday::Response", :body => can_update_true.to_json)) expect(described_class.new(api, raw_instance).can_update?).to be_truthy end it 'returns false' do expect(api).to receive(:get).and_return(instance_double("Faraday::Response", :body => can_update_false.to_json)) expect(described_class.new(api, raw_instance).can_update?).to be_falsey end end describe '#update' do let(:post_result_body) { {:inventory_update => 1} } it "updates an inventory_source" do expect_any_instance_of(AnsibleTowerClient::Collection).to receive(:find).with(post_result_body[:project_update]) expect(api).to receive(:post).and_return(instance_double("Faraday::Response", :body => post_result_body.to_json)) described_class.new(api, raw_instance).update end end describe '#last_update' do let(:project_update) { AnsibleTowerClient::ProjectUpdate.new(api, 'id' => 123) } it "fetches last update" do collection_double = instance_double("AnsibleTowerClient::Collection") expect(api).to receive(:project_updates).and_return(collection_double) expect(collection_double).to receive(:find).with(raw_instance['related']['last_update']).and_return(project_update) actual_instance = described_class.new(api, raw_instance).last_update expect(actual_instance).to equal(project_update) end it "does not fetch last update if missing" do raw_instance['related'].delete('last_update') result = described_class.new(api, raw_instance).last_update expect(result).to be_nil end it "does not fetch last update if nil" do raw_instance['related']['last_update'] = nil result = described_class.new(api, raw_instance).last_update expect(result).to be_nil end end end
lfu/ansible_tower_client_ruby
spec/system_job_template_spec.rb
describe AnsibleTowerClient::SystemJobTemplate do let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :system_job_template, :klass => described_class) } describe "#launch" do let(:post_result_body) { {:system_job => 123} } it "runs a job template and returns the created system job" do launch_url = "#{raw_instance["url"]}launch/" launch_vars = {"days" => 10} response_double = instance_double("Faraday::Response", :body => post_result_body.to_json) expect_any_instance_of(AnsibleTowerClient::Collection).to receive(:find).with(123) expect(api).to receive(:post).with(launch_url, "extra_vars" => launch_vars).and_return(response_double) described_class.new(api, raw_instance).launch(launch_vars) end end end
lfu/ansible_tower_client_ruby
spec/workflow_job_template_spec.rb
<filename>spec/workflow_job_template_spec.rb describe AnsibleTowerClient::WorkflowJobTemplate do let(:url) { "example.com/api/v1/workflow_job_templates" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new("1.1"), 1) } let(:raw_instance) { build(:response_instance, :workflow_job_template, :klass => described_class) } let(:raw_instance_no_extra_vars) { build(:response_instance, :workflow_job_template, :klass => described_class, :extra_vars => '') } let(:raw_instance_no_survey) { build(:response_instance, :workflow_job_template, :klass => described_class, :related => {}) } include_examples "Api Methods" include_examples "Crud Methods" describe '#launch' do let(:json_params) { {'extra_vars' => "{\"instance_ids\":[\"i-999c\"],\"state\":\"absent\",\"subnet_id\":\"subnet-887\"}"} } let(:post_result_body) { {:workflow_job => 1} } it "runs an existing job template" do launch_url = "#{raw_instance["url"]}launch/" response_double = instance_double("Faraday::Response", :body => post_result_body.to_json) expect_any_instance_of(AnsibleTowerClient::Collection).to receive(:find).with(post_result_body[:workflow_job]) expect(api).to receive(:post).with(launch_url, json_params).and_return(response_double) described_class.new(api, raw_instance).launch(json_params) end end context "#initialize" do it "#initialize instantiates an #{described_class} from a hash" do obj = api.workflow_job_templates.all.first expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.name).to be_a String expect(obj.description).to be_a String expect(obj.related).to be_a described_class::Related expect(obj.extra_vars).to eq("hosts:\n- inky\n- pinky\n- clyde\n- sue'") end end context "#survey_spec" do describe "exists" do let(:survey_spec) { "{\"description\":\"blah\"}" } it "returns a survey spec" do expect(api).to receive(:get).and_return(instance_double("Faraday::Result", :body => survey_spec)) expect(described_class.new(api, raw_instance).survey_spec).to eq(survey_spec) end end it "does not exist to return nil" do expect(described_class.new(api, raw_instance_no_survey).survey_spec).to be_nil end it "unlicensed to return a survey spec" do expect(api).to receive(:get).and_raise(AnsibleTowerClient::UnlicensedFeatureError) expect(described_class.new(api, raw_instance).survey_spec).to be_nil end end context "#survey_spec_hash" do describe "exists" do let(:survey_spec) { "{\"description\":\"blah\"}" } it "returns a hashed value" do expect(api).to receive(:get).twice.and_return(instance_double("Faraday::Result", :body => survey_spec)) expect(described_class.new(api, raw_instance).survey_spec_hash).to eq("description" => "blah") end end it "does not exist to return an empty hash" do expect(described_class.new(api, raw_instance_no_survey).survey_spec_hash).to be_empty expect(described_class.new(api, raw_instance_no_survey).survey_spec_hash).to be_a_kind_of(Hash) end end context "#extra_vars_hash" do it "exists to return a hashed value" do obj = described_class.new(instance_double("AnsibleTowerClient::Api"), raw_instance) expect(obj.extra_vars_hash).to eq('option' => 'lots of options') end it "does not exist to return an empty hash" do obj = described_class.new(instance_double("AnsibleTowerClient::Api"), raw_instance_no_extra_vars) expect(obj.extra_vars_hash).to be_a_kind_of(Hash) expect(obj.extra_vars_hash).to be_empty end end context 'override_raw_attributes' do let(:obj) { described_class.new(AnsibleTowerClient::MockApi.new, raw_instance) } let(:instance_api) { obj.instance_variable_get(:@api) } it 'translates :organization to :organization_id for update_attributes' do raw_instance[:organization_id] = 10 expect(instance_api).to receive(:patch).and_return(instance_double("Faraday::Result", :body => raw_instance.to_json)) expect(obj.update_attributes(:organization => '5')).to eq true expect(obj.organization_id).to eq '5' end end end
lfu/ansible_tower_client_ruby
lib/ansible_tower_client/v2/credential_type_v2.rb
<reponame>lfu/ansible_tower_client_ruby module AnsibleTowerClient class CredentialTypeV2 < BaseModel class Inputs < BaseModel; end def self.endpoint 'credential_types' end end end
lfu/ansible_tower_client_ruby
lib/ansible_tower_client/connection.rb
module AnsibleTowerClient class Connection attr_reader :options # Options: # - base_url: you have two options here: # a) pass in only scheme and hostname e.g. 'https://localhost:54321' to allow client to connect to both api v1 # and v2 versions like this: `client.api(:version => 1)` and `client.api(:version => 2)`. This requires ansible # tower API being accessible directly at `https://localhost:54321/api/v1` and `https://localhost:54321/api/v2`. # b) pass in a complete api address e.g. 'https://localhost:54321/tower'. Client will then connect to the path # directly and it's your responsibility to know what version of API is there. # - username # - password # - verify_ssl def initialize(options = {}) raise "Credentials are required" unless options[:username] && options[:password] raise ":base_url is required" unless options[:base_url] logger = options[:logger] || AnsibleTowerClient.logger require 'faraday' require 'faraday_middleware' require 'ansible_tower_client/middleware/raise_tower_error' Faraday::Response.register_middleware :raise_tower_error => -> { Middleware::RaiseTowerError } @options = { :url => options[:base_url], :verify_ssl => (options[:verify_ssl] || OpenSSL::SSL::VERIFY_PEER) != OpenSSL::SSL::VERIFY_NONE, :username => options[:username], :password => options[:password], :logger => logger, } reset end def connection(url:, username:, password:, verify_ssl: false, logger: nil) Faraday.new(url, :ssl => {:verify => verify_ssl}) do |f| f.use(FaradayMiddleware::EncodeJson) f.use(FaradayMiddleware::FollowRedirects, :limit => 3, :standards_compliant => true) f.request(:url_encoded) f.response(:raise_tower_error) f.response(:logger, logger) f.adapter(Faraday.default_adapter) f.basic_auth(username, password) end end def api(version: 2) @api[version] ||= begin # Build uri path. options = @options.clone.tap do |opts| opts[:url] = URI(opts[:url]).tap { |url| url.path = url_path_for_version(url.path, version) } end Api.new(connection(**options), version) end end def reset @api = {} end private def url_path_for_version(orig_path, api_version) return orig_path unless orig_path.sub(/\/$/, "").empty? "/api/v#{api_version}" end end end
lfu/ansible_tower_client_ruby
spec/connection_spec.rb
<gh_stars>0 describe AnsibleTowerClient::Connection do let(:logger) { double } let(:base_options) { {:base_url => "https://example1.com", :username => "admin", :password => "<PASSWORD>", :verify_ssl => OpenSSL::SSL::VERIFY_NONE, :logger => logger} } subject { described_class.new(base_options) } it "#initialize returns a connection instance" do expect(described_class.new(base_options)).to be_a AnsibleTowerClient::Connection end it "#initialize sets options" do expect(subject.options).to eq( :url => "https://example1.com", :verify_ssl => false, :username => "admin", :password => "<PASSWORD>", :logger => logger, ) end it ".new doesn't cache credentials across all instances" do conn_1 = described_class.new(base_options) conn_2 = described_class.new(base_options.merge(:base_url => "https://example2.com", :username => "user", :password => "password")) expect(conn_1.api.instance).not_to eq(conn_2.api.instance) end context ".api" do it "defaults to api v2" do expect(subject.api.api_version).to eq(2) end it "supports api v1" do expect(subject.api(:version => 1).api_version).to eq(1) end it "dynamic switching between v1 and v2 won't interfere" do expect(subject.api(:version => 1).api_version).to eq(1) expect(subject.api(:version => 2).api_version).to eq(2) expect(subject.api(:version => 1).api_version).to eq(1) expect(subject.api(:version => 2).api_version).to eq(2) end end context ".url_path_for_version" do [ { :case => "basic base url", :base_url => "", :expected_url_v1 => "/api/v1", :expected_url_v2 => "/api/v2" }, { :case => "hash-ended base url", :base_url => "/", :expected_url_v1 => "/api/v1", :expected_url_v2 => "/api/v2" }, { :case => "custom base url", :base_url => "/custom/api/path", :expected_url_v1 => "/custom/api/path", :expected_url_v2 => "/custom/api/path" } ].each do |args| it args[:case].to_s do expect(subject.send(:url_path_for_version, args[:base_url], 1)).to eq(args[:expected_url_v1]) expect(subject.send(:url_path_for_version, args[:base_url], 2)).to eq(args[:expected_url_v2]) end end end end
lfu/ansible_tower_client_ruby
lib/ansible_tower_client/version.rb
<filename>lib/ansible_tower_client/version.rb module AnsibleTowerClient VERSION = "0.15.0".freeze end
lfu/ansible_tower_client_ruby
spec/support/mock_api/v2/credential_type.rb
module AnsibleTowerClient class MockApi module CredentialTypeV2 def self.collection [ { :id => 16, :type => "credential_type", :url => "/api/v2/credential_types/16/", :related => { :created_by => "/api/v2/users/1/", :modified_by => "/api/v2/users/1/", :credentials => "/api/v2/credential_types/16/credentials/", :activity_stream => "/api/v2/credential_types/16/activity_stream/" }, :summary_fields => { :created_by => {:id => 1, :username => "admin", :first_name => "", :last_name => ""}, :modified_by => {:id => 1, :username => "admin", :first_name => "", :last_name => ""}, :user_capabilities => {:edit => true, :delete => true} }, :created => "2018-06-18T20:02:15.415325Z", :modified => "2018-06-18T20:02:15.415353Z", :name => "Nuage", :description => "", :kind => "cloud", :managed_by_tower => false, :inputs => { :fields => [ {:type => "string", :id => "nuage_username", :label => "Username"}, {:secret => true, :type => "string", :id => "nuage_password", :label => "Password"}, {:type => "string", :id => "nuage_enterprise", :label => "Enterprise"}, {:type => "string", :id => "nuage_url", :label => "URL"}, {:choices => %w(v4_0 v5_0), :type => "string", :id => "nuage_version", :label => "Version"} ], :required => %w(nuage_username nuage_password nuage_enterprise nuage_url nuage_version) }, :injectors => { :extra_vars => { :nuage_username => "{{ nuage_username }}", :nuage_password => "{{ <PASSWORD> }}", :nuage_version => "{{ nuage_version }}", :nuage_enterprise => "{{ nuage_enterprise }}", :nuage_url => "{{ nuage_url }}" } } } ] end def self.response { "count" => collection.length, "next" => nil, "previous" => nil, "results" => collection }.to_json end end end end
lfu/ansible_tower_client_ruby
spec/workflow_job_node_spec.rb
describe AnsibleTowerClient::WorkflowJobNode do let(:url) { "example.com/api/v1/workflow_job_nodes" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :workflow_job_node, :klass => described_class) } include_examples "Api Methods" include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.workflow_job_nodes.all.first expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.job_id).to be_a Integer expect(obj.workflow_job_id).to be_a Integer expect(obj.related).to be_a described_class::Related end end
lfu/ansible_tower_client_ruby
spec/workflow_job_spec.rb
<reponame>lfu/ansible_tower_client_ruby describe AnsibleTowerClient::WorkflowJob do let(:url) { "example.com/api/v1/workflow_jobs" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :workflow_job, :klass => described_class) } include_examples "Api Methods" include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.workflow_jobs.all.first expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.name).to be_a String expect(obj.workflow_job_nodes).to be_a Enumerator expect(obj.related).to be_a described_class::Related end end
lfu/ansible_tower_client_ruby
spec/inventory_spec.rb
<gh_stars>0 describe AnsibleTowerClient::Inventory do let(:url) { "example.com/api/v1/inventories" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:inventory_source) { build(:response_url_collection, :klass => AnsibleTowerClient::InventorySource) } let(:raw_instance) { build(:response_instance, :klass => described_class) } let(:instance) { api.inventories.all.first } include_examples "Api Methods" include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do expect(instance).to be_a described_class expect(instance.id).to be_a Integer expect(instance.name).to be_a String end describe "#inventory_sources" do it "#inventory_sources returns a list of inventory_sources" do expect_any_instance_of(described_class).to receive(:related).and_return("inventory_sources" => "abc") expect(api).to receive(:get).and_return(instance_double("Faraday::Result", :body => inventory_source.to_json)) inventory_sources = described_class.new(api, raw_instance).inventory_sources.to_a expect(inventory_sources.to_a.count).to eq 1 end end describe "#update_all_inventory_sources" do let(:can_update_true) { {'can_update' => true} } let(:can_update_false) { {'can_update' => false} } let(:post_result_body) { {:inventory_update => 1} } let(:inventory_sources) do [described_class.new(instance_double("AnsibleTowerClient::Api"), inventory_source)] end before do expect(instance).to receive(:inventory_sources).and_return(inventory_sources) end it "updates an inventory_source if #can_update? is true" do expect(inventory_sources.first).to receive(:can_update?).and_return(can_update_true['can_update']) expect(inventory_sources.first).to receive(:update).once.and_return(post_result_body) instance.update_all_inventory_sources end it "does not update an inventory_source if #can_update? is false" do expect(inventory_sources.first).to receive(:can_update?).and_return(can_update_false['can_update']) instance.update_all_inventory_sources end end end
lfu/ansible_tower_client_ruby
spec/v2/credential_type_spec.rb
describe AnsibleTowerClient::CredentialTypeV2 do let(:api) { AnsibleTowerClient::Api.new(connection, 2) } let(:connection) { AnsibleTowerClient::MockApi.new } let(:raw_instance) { build(:response_instance, :credential_type, :klass => described_class) } include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.credential_types.all.detect { |cred| cred.name == 'Nuage' } expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.url).to be_a String expect(obj.name).to be_a String expect(obj.kind).to be_a String expect(obj.managed_by_tower).to eq false expect(obj.inputs).to be_a AnsibleTowerClient::CredentialTypeV2::Inputs expect(obj.inputs.fields).to be_a Array expect(obj.inputs.required).to be_a Array expect(obj.injectors).to be_a AnsibleTowerClient::CredentialTypeV2::Injectors end context 'override_raw_attributes' do let(:obj) { described_class.new(instance_double("Faraday::Connection"), raw_instance) } let(:instance_api) { obj.instance_variable_get(:@api) } end end
lfu/ansible_tower_client_ruby
lib/ansible_tower_client/base_models/workflow_job.rb
<gh_stars>0 module AnsibleTowerClient class WorkflowJob < BaseModel def workflow_job_nodes # this is where Ansible API deviates from other part by using `workflow_nodes` Collection.new(api).find_all_by_url(related['workflow_nodes']) end end end
lfu/ansible_tower_client_ruby
spec/job_spec.rb
describe AnsibleTowerClient::Job do let(:url) { "example.com/api/v1/jobs" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :job, :klass => described_class) } let(:raw_instance_no_extra_vars) { build(:response_instance, :job_template, :klass => described_class, :extra_vars => '') } let(:raw_instance_no_output) { build(:response_instance, :job_template, :klass => described_class, :related => {}) } include_examples "Api Methods" include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.jobs.all.first expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.name).to be_a String expect(obj.related).to be_a described_class::Related end describe "#extra_vars_hash" do describe "#extra_vars exists" do it "returns a hashed value" do obj = described_class.new(AnsibleTowerClient::MockApi.new, raw_instance) expect(obj.extra_vars_hash).to eq('option' => 'lots of options') end end describe "#extra_vars does not exist" do it "returns an empty hash" do obj = described_class.new(AnsibleTowerClient::MockApi.new, raw_instance_no_extra_vars) expect(obj.extra_vars_hash).to eq({}) end end end context '#job_events' do let(:url) { "example.com/api/v1/job_events" } let(:job_collection) { build(:response_collection, :klass => described_class) } let(:job_events) { build(:response_url_collection, :klass => AnsibleTowerClient::JobEvent, :url => url) } it "returns a collection of AnsibleTowerClient::JobEvents" do expect(AnsibleTowerClient::Collection).to receive(:new).with(api, api.job_event_class).and_return(job_collection) expect(job_collection).to receive(:find_all_by_url).and_return(job_events['results']) results = described_class.new(api, raw_instance).job_events.first expect(results).to include( "type" => "job_event", "url" => "example.com/api/v1/job_events", ) end end context '#stdout' do describe "exists" do let(:stdout) { "Ansible Tower job output" } it "returns stdout default to plain text" do expect(api).to receive(:get).with(/format=txt/).and_return(instance_double("Faraday::Result", :body => stdout)) expect(described_class.new(api, raw_instance).stdout).to eq(stdout) end it "returns formatted text per request" do expect(api).to receive(:get).with(/format=html/).and_return(instance_double("Faraday::Result", :body => stdout)) expect(described_class.new(api, raw_instance).stdout('html')).to eq(stdout) end end describe "does not exist" do it "returns nil" do expect(described_class.new(api, raw_instance_no_output).stdout).to be_nil end end end end
lfu/ansible_tower_client_ruby
lib/ansible_tower_client/v2/credential_v2.rb
<gh_stars>0 module AnsibleTowerClient class CredentialV2 < Credential class Inputs < BaseModel def size @raw_hash.keys.size end end def self.endpoint 'credentials' end end end
lfu/ansible_tower_client_ruby
spec/job_event_spec.rb
<gh_stars>0 describe AnsibleTowerClient::JobEvent do let(:url) { "example.com/api/v1/job_events" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } include_examples "Api Methods" end
lfu/ansible_tower_client_ruby
spec/host_spec.rb
<gh_stars>0 describe AnsibleTowerClient::Host do let(:url) { "example.com/api/v1/hosts" } let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :host, :klass => described_class) } include_examples "Api Methods" include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.hosts.all.first expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.url).to be_a String expect(obj.instance_id).to be_a String expect(obj.inventory_id).to be_a Integer expect(obj.name).to be_a String end end
lfu/ansible_tower_client_ruby
spec/organization_spec.rb
<filename>spec/organization_spec.rb describe AnsibleTowerClient::Organization do let(:api) { AnsibleTowerClient::Api.new(AnsibleTowerClient::MockApi.new, 1) } let(:raw_instance) { build(:response_instance, :organization, :klass => described_class, :description => "The Organization", :name => "MyOrg") } include_examples "Crud Methods" it "#initialize instantiates an #{described_class} from a hash" do obj = api.organizations.all.first expect(obj).to be_a described_class expect(obj.id).to be_a Integer expect(obj.url).to be_a String expect(obj.description).to eq "The Organization" expect(obj.name).to be_a String end end
diverse-inc/rsolr-ext
lib/rsolr-ext/response.rb
module RSolr::Ext::Response autoload :Docs, 'rsolr-ext/response/docs' autoload :Facets, 'rsolr-ext/response/facets' autoload :Spelling, 'rsolr-ext/response/spelling' class Base < Mash attr :original_hash attr_reader :request_path, :request_params def initialize hash, handler, request_params super hash @original_hash = hash @request_path, @request_params = request_path, request_params extend Response extend Docs extend Facets extend Spelling end def header self['responseHeader'] end def rows params[:rows]&.first&.to_i end def params (header and header['params']) ? header['params'] : request_params end def ok? (header and header['status']) ? header['status'] == 0 : nil end def method_missing *args, &blk self.original_hash.send *args, &blk end end module Response def response self[:response] end # short cut to response['numFound'] def total response[:numFound].to_s.to_i end def start response[:start].to_s.to_i end end end
Kelthagas/mr_sorty_batallones
lib/mr_sorty/heapsort_min.rb
module HeapsortMin class HeapsortMin def initialize arr @minheap = [] @minheap = arr end def get_array return @minheap end def return_heap arr = [] @minheap.each do |node| arr.push(remove_node) end return arr end def insert_node end def remove_node return 0 end private def bubble_up end def bubble_down end end end
Kelthagas/mr_sorty_batallones
spec/mr_sorty_spec.rb
<gh_stars>0 RSpec.describe MrSorty do it "has a version number" do expect(MrSorty::VERSION).not_to be nil end it "does something useful" do sort = HeapsortMin::HeapsortMin.new [1, 2, 3] expect(sort.return_heap).to eq([0, 0, 0]) end end
Kelthagas/mr_sorty_batallones
lib/mr_sorty.rb
<filename>lib/mr_sorty.rb require "mr_sorty/version" require "mr_sorty/heapsort_min" module MrSorty end
soichikamiya/sample-app2
spec/system/following_spec.rb
require 'rails_helper' RSpec.describe 'フォローページ', type: :system do context "" do # Applicationヘルパーを読み込むと full_titleヘルパー が利用できる include ApplicationHelper let(:login_method) do post login_url, params: { session: { email: @user.email, password: "password" } } expect(session[:user_id]).to eq(@user.id) expect(response).to redirect_to @user end let(:create_relationship) do rel = [:relationship,:relationship1,:relationship2,:relationship3] 4.times { |n| create(rel[n]) } end before do @user = create(:testuser) 3.times { create(:user) } end it 'following page' do login_method create_relationship get following_user_path(@user) expect(response).to render_template 'users/show_follow' expect(@user.following.empty?).to eq(false) expect(response.body).to have_content @user.following.count.to_s expect(response.body).to have_content @user.following.count expect(@user.following.count).to eq(2) @user.following.each do |user| expect(response.body).to have_selector "a[href='#{user_path(user)}']" end end it 'followers page' do login_method create_relationship get followers_user_path(@user) expect(response).to render_template 'users/show_follow' expect(@user.followers.empty?).to eq(false) expect(response.body).to have_content @user.followers.count.to_s expect(response.body).to have_content @user.followers.count.to_s expect(@user.followers.count).to eq(2) @user.followers.each do |user| expect(response.body).to have_selector "a[href='#{user_path(user)}']" end end it "html通信(通常通信)でユーザーをフォローする" do login_method @other = User.second expect { post relationships_path, params: { followed_id: @other.id } }.to change(@user.following, :count).by(1) end it "ajax通信でユーザーをフォローする" do login_method @other = User.second # xhr (XmlHttpRequest) というオプションをtrueに設定し、Ajaxでリクエストを発行するよう変更 expect { post relationships_path, xhr: true, params: { followed_id: @other.id } }.to change(@user.following, :count).by(1) end it "html通信(通常通信)でユーザーをアンフォローする" do login_method @other = User.second @user.follow(@other) relationship = @user.active_relationships.find_by(followed_id: @other.id) expect { delete relationship_path(relationship) }.to change(@user.following, :count).by(-1) end it "ajax通信でユーザーをアンフォローする" do login_method @other = User.second @user.follow(@other) relationship = @user.active_relationships.find_by(followed_id: @other.id) # xhr (XmlHttpRequest) というオプションをtrueに設定し、Ajaxでリクエストを発行するよう変更 expect { delete relationship_path(relationship), xhr: true }.to change(@user.following, :count).by(-1) end # 「14章3.3 サブセレクト」最終の演習わかりにくい、、 it "Homeページのfeed確認" do login_method @micropost = create(:orange) get root_path @user.feed.paginate(page: 1).each do |micropost| expect(response.body).to have_content CGI.escapeHTML(micropost.content) end end end end
soichikamiya/sample-app2
spec/models/relationship_spec.rb
require 'rails_helper' RSpec.describe Relationship, type: :model do context 'Relationship作成の確認' do before do 2.times { create(:user) } @relationship = Relationship.new(follower_id: User.first.id, followed_id: User.second.id) end it "有効かどうか" do expect(@relationship).to be_valid end it "follower_idは必須かどうか" do @relationship.follower_id = nil expect(@relationship).not_to be_valid end it "followed_idは必須かどう" do @relationship.followed_id = nil expect(@relationship).not_to be_valid end end end
soichikamiya/sample-app2
spec/controllers/relationships_controller_spec.rb
<filename>spec/controllers/relationships_controller_spec.rb require 'rails_helper' RSpec.describe RelationshipsController, type: :controller do context "Relationshipsアクション確認" do it "作成する際ログインが必要" do expect { post :create }.not_to change(Relationship, :count) assert_redirected_to login_url end it "削除する際ログインが必要" do 2.times { create(:user) } relationship = create(:relationship) expect { delete :destroy, params: { id: relationship.id }}.not_to change(Relationship, :count) assert_redirected_to login_url end end end
soichikamiya/sample-app2
spec/system/static_pages_controller_spec.rb
require 'rails_helper' RSpec.describe '静的ページ確認', type: :system do describe '各画面の表示確認' do let(:url_root) { visit root_path } let(:help_url) { visit help_path } let(:about_url) { visit about_path } let(:contact_url) { visit contact_path } before do @base_title = "Ruby on Rails Tutorial Sample App" end # js: trueでchromeを開きエラーの際Screenshot shared_examples_for '画面に Ruby on Rails が表示されている', js: true do it { expect(page).to have_content "Ruby on Rails" } end shared_examples_for 'タイトルが正常に表示されている' do it { expect(page).to have_title "#{@base_title}" } end context 'ルートURLの時' do before do url_root end it_behaves_like '画面に Ruby on Rails が表示されている' it_behaves_like 'タイトルが正常に表示されている' it '各リンクが表示されている', js: true do expect(page).to have_selector 'h1', text: 'Welcome to the Sample App' expect(page).to have_selector 'a[href="/"]', count: 2 expect(page).to have_selector 'a[href="/help"]', text: 'Help', count: 2 expect(page).to have_selector 'a[href="/about"]', text: 'About' expect(page).to have_selector 'a[href="/contact"]', text: 'Contact' end end context 'ヘルプURLの時' do before do help_url end it_behaves_like '画面に Ruby on Rails が表示されている' it 'タイトルが正常に表示されている' do expect(page).to have_title "Help | #{@base_title}" end end context 'アバウトURLの時' do before do about_url end it_behaves_like '画面に Ruby on Rails が表示されている' it 'タイトルが正常に表示されている' do expect(page).to have_title "About | #{@base_title}" end end context 'コンタクトURLの時' do before do contact_url end it_behaves_like '画面に Ruby on Rails が表示されている' it 'タイトルが正常に表示されている' do expect(page).to have_title "Contact | #{@base_title}" end end context 'サインアップURLの時' do before do visit signup_path end it_behaves_like '画面に Ruby on Rails が表示されている' it 'タイトルが正常に表示されている' do expect(page).to have_title "Sign up | #{@base_title}" end end end end
soichikamiya/sample-app2
spec/system/users_index_spec.rb
require 'rails_helper' RSpec.describe 'ユーザー一覧', type: :system do describe '一覧ページ' do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser) 31.times { create(:user) } end it 'ページネーションが含まれているかどうか' do visit login_path fill_in 'Email', with: @user.email fill_in 'Password', with: 'password' click_on 'login-id' visit users_path expect(page).to have_content "All users" expect(page).to have_selector 'div.pagination', count: 2 User.paginate(page: 1).each do |user| expect(page).to have_selector "a[href='/users/#{user.id}']", text: user.name end end end describe '一覧ページ削除' do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") 31.times { create(:user) } end it 'ログインしていない場合ログインページに遷移すること' do delete user_url(User.second) expect(response).to have_http_status(302) expect(response).to redirect_to login_url end it 'adminユーザーでログインしていない場合ログインページに遷移すること' do visit login_path fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: '<PASSWORD>' click_on 'login-id' delete user_url(User.second) expect(response).to have_http_status(302) expect(response).to redirect_to login_url end it 'adminユーザーだと削除が表示' do visit login_path fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: 'password' click_on 'login-id' visit users_path expect(page).to have_content "All users" expect(page).to have_selector 'div.pagination', count: 2 User.paginate(page: 1).each do |user| expect(page).to have_selector "a[href='/users/#{user.id}']", text: user.name unless user == @user expect(page).to have_selector "a[href='/users/#{user.id}']", text: "delete" end end end it 'adminユーザー以外だと削除非表示',js:true do @user.update_attribute(:admin, false) visit login_path fill_in 'Email', with: @user.email fill_in 'Password', with: 'password' click_on 'login-id' visit users_path expect(page).to have_content "All users" expect(page).to have_selector 'div.pagination', count: 2 User.paginate(page: 1).each do |user| expect(page).to have_selector "a[href='/users/#{user.id}']", text: "delete", count: 0 end end it 'adminユーザーだと削除可能' do post login_url, params: { session: { email: "<EMAIL>", password: "password", remember_me: 1 } } expect { delete user_url(User.second) }.to change(User, :count).by(-1) expect(response).to have_http_status(302) expect(flash[:success]).to eq("User deleted") expect(response).to redirect_to users_url end it 'adminユーザー以外だと削除不可' do @user.update_attribute(:admin, false) post login_url, params: { session: { email: "<EMAIL>", password: "password", remember_me: 0 } } expect { delete user_url(User.second) }.to change(User, :count).by(0) expect(response).to have_http_status(302) expect(flash[:success]).to eq(nil) expect(response).to redirect_to root_url end end end
soichikamiya/sample-app2
spec/system/users_edit_spec.rb
require 'rails_helper' RSpec.describe 'ユーザーの編集', type: :system do describe 'flashメッセージの確認' do context "編集が失敗する事" do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") end it '名前を空欄にすると画面遷移しない' do visit login_path fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: 'password' click_on 'login-id' visit edit_user_path(@user) fill_in 'Name', with: "" fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: 'password' fill_in 'Confirmation', with: 'password' click_on 'Save changes' expect(page).to have_http_status(:success) expect(current_path).to eq user_path(@user) expect(page).to have_content "Update your profile" expect(page).to have_selector 'div.alert', text: 'The form contains' end it 'ログインしていない場合ログインページに遷移されること(画面側)' do visit edit_user_path(@user) expect(page).to have_http_status(:success) expect(current_path).to eq login_path expect(page).to have_content "Please log in." end it 'ログインしていない場合ログインページに遷移されること(サーバー側)' do patch user_url(@user), params: { user: { name: @user.name, email: @user.email } } expect(response).to have_http_status(302) expect(response).to redirect_to login_path expect(flash[:danger]).to eq "Please log in." end end end end
soichikamiya/sample-app2
spec/factories/users.rb
FactoryBot.define do factory :user do # データを生成する毎に通し番号をふってユニークな値を作る sequence(:name) { |n| "TestName-#{n}"} sequence(:email) { |n| "<EMAIL>"} sequence(:password) { |n| "<PASSWORD>}"} sequence(:password_confirmation) { |n| "<PASSWORD>}"} activated { true } activated_at { Time.zone.now } end # Userクラスでモデル名以外の名前を作成 factory :testuser, class: User do name { "TaroTanaka" } email { "<EMAIL>" } # password_digest { User.digest("password") } password { "password" } password_confirmation { "password" } admin { true } activated { true } activated_at { Time.zone.now } end # activation用のUserクラスを作成 factory :activated_user, class: User do name { "TaroTanaka" } email { "<EMAIL>" } # password_digest { User.digest("password") } password { "password" } password_confirmation { "password" } admin { false } activated { false } activated_at { nil } end end
soichikamiya/sample-app2
spec/system/microposts_interface_test.rb
<reponame>soichikamiya/sample-app2 require 'rails_helper' RSpec.describe 'マイクロポストテスト', type: :system do context '各テスト' do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") end it '' do post login_url, params: { session: { email: @user.email, password: "password" } } expect(session[:user_id]).to eq(@user.id) # 無効な送信 expect { post microposts_path, params: { micropost: { content: "" } } }.to change(Micropost, :count).by(0) # 有効な送信 content = "This micropost really ties the room together" expect { post microposts_path, params: { micropost: { content: content } } }.to change(Micropost, :count).by(1) expect(response).to redirect_to root_url # 投稿を削除する micropost = @user.microposts.first expect { delete micropost_path(micropost) }.to change(Micropost, :count).by(-1) # 違うユーザーのポストを削除 @user2 = create(:user) micropost2 = create(:micropost, user: @user2) expect { delete micropost_path(micropost2) }.to change(Micropost, :count).by(0) expect(response).to redirect_to root_url end end end
soichikamiya/sample-app2
spec/system/users_login_spec.rb
<reponame>soichikamiya/sample-app2<gh_stars>0 require 'rails_helper' RSpec.describe 'ユーザーログイン', type: :system do describe 'flashメッセージの確認' do context "サーバー側で処理" do it '無効なログインではflashが表示されページ遷移すると消える' do post login_url, params: { session: { email: "<EMAIL>", password: "<PASSWORD>" } } expect(response).to render_template :new expect(flash.present?).to eq(true) # visitはサーバー処理では無い為 flashの存在を引き継ぐ事になる # visit root_path get root_path expect(flash[:danger]).not_to be_present end end context "ビュー側で処理理" do it '無効なログインではflashが表示されページ遷移すると消える' do # 画面上のみなので response や flash のサーバー処理は使えない visit login_path fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: '<PASSWORD>' click_on 'login-id' expect(page).to have_content 'New user? Sign up now!' expect(page).to have_selector 'div.alert-danger', text: 'Invalid email/password combination' visit root_path expect(page).not_to have_selector 'div.alert-danger' end end end context '正しい値でログイン' do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") end it 'ログイン後セッション値が登録される(サーバー)' do post login_url, params: { session: { email: "<EMAIL>", password: "password" } } expect(session[:user_id]).to eq(@user.id) expect(response).to redirect_to @user follow_redirect! #上記リダイレクト先に移動する (無くても下記のvisitで遷移可能?) visit user_path(@user) expect(page).to have_link 'Help' #なぜかログイン状態にならない end it 'ログイン後リンク表示の確認(ビュー)' do visit login_path fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: 'password' click_on 'login-id' visit current_url click_on 'Account' expect(page).to have_selector 'a[href="/login"]', text: 'Log in', count: 0 expect(page).to have_selector 'a[href="/logout"]', text: 'Log out', count: 1 expect(page).to have_selector "a[href='/users/1']", text: "Profile" expect(page).to have_link 'Users' expect(page).to have_link 'Log in', href: login_path, count: 0 expect(page).to have_link 'Log out', href: logout_path expect(page).to have_link 'Profile', href: user_path(@user), count: 1 end end context 'ログイン後のログアウト確認' do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") end it do visit login_path fill_in 'Email', with: '<EMAIL>' fill_in 'Password', with: 'password' click_on 'login-id' visit current_url click_on 'Account' expect(page).to have_link 'Log in', href: login_path, count: 0 expect(page).to have_link 'Log out', href: logout_path, count: 1 expect(page).to have_link 'Profile', href: user_path(@user), count: 1 # サーバー処理 expect do post login_url, params: { session: { email: "<EMAIL>", password: "password", remember_me: 1 } } end.not_to change(User, :count) expect(response).to have_http_status(302) expect(session[:user_id]).to eq(@user.id) expect(cookies[:user_id]).to be_present expect(cookies[:remember_token]).to be_present delete logout_url expect(response).to have_http_status(302) expect(session[:user_id]).to eq(nil) expect(response).to redirect_to root_url visit root_url # ログアウトしてるのに何故かログイン状態のヘッダーになる expect(page).to have_link 'Log in', href: login_path, count: 0 click_on 'Account' click_on 'Log out' expect(response).to have_http_status(302) expect(page).to have_content "Welcome to the Sample App" expect(page).not_to have_content "Account" expect(page).to have_link 'Log in', href: login_path, count: 1 expect(page).to have_link 'Log out', href: logout_path, count: 0 expect(page).to have_link 'Profile', href: user_path(@user), count: 0 end end end
soichikamiya/sample-app2
spec/models/micropost_spec.rb
require 'rails_helper' RSpec.describe Micropost, type: :model do context "micropostの有効性" do before do @user = create(:user, name: "SoichiKamiya") # FactoryBot.build(:user)を短縮 createだとDB登録される # @micropost = Micropost.new(content: "Lorem ipsum", user_id: @user.id) @micropost = @user.microposts.build(content: "Lorem ipsum") end it "有効かどうか" do expect(@micropost.valid?).to eq(true) expect(@micropost).to be_valid end it "ユーザーidが必須であること" do @micropost.user_id = nil expect(@micropost).not_to be_valid end it 'contentが空だとNG' do @micropost.content = "" expect(@micropost).not_to be_valid end it "contentが必須であること" do @micropost.content = "  " expect(@micropost).not_to be_valid end it "contentは最低140文字以下であること" do @micropost.content = "a" * 141 expect(@micropost).not_to be_valid end end context "micropostとユーザーの関係" do before do @user = create(:user, name: "SoichiKamiya") # FactoryBot.build(:user)を短縮 createだとDB登録される [:orange, :tau_manifesto, :cat_video, :most_recent].each { |m| create(m) } @micropost = Micropost.find_by(content: "Writing a short test") end it "最新が最初に来るかどうか" do # default_scope -> { order(created_at: :desc) } で降順になっているため新しいのが最初に来てる expect(@micropost).to eq(Micropost.first) end it "関連するmicropostsも削除されること" do expect(@user.microposts.count).to eq(4) expect{ @user.destroy }.to change(Micropost, :count).by(-4) end end end
soichikamiya/sample-app2
spec/models/user_spec.rb
<reponame>soichikamiya/sample-app2 require 'rails_helper' RSpec.describe User, type: :model do context 'ユーザー作成の確認' do before do @user = build(:user) # FactoryBot.build(:user)を短縮 createだとDB登録される # @user = User.new(name: 'Tom', email: '<EMAIL>') end it 'validかどうか' do # trueかfalseの表示しかしない expect(@user.valid?).to eq(true) # 有効性確認の為 @userの中を表示する # expect(@user).not_to be_valid end it 'nameが空だとNG' do @user.name = '' expect(@user).not_to be_valid end it 'emailが空だとNG' do @user.email = ' ' expect(@user).not_to be_valid end it "nameが51文字以上だとNG" do @user.name = 'a' * 51 expect(@user).not_to be_valid end it "emailが255文字以上だとNG" do @user.email = 'a' * 244 + '@example.com' expect(@user).not_to be_valid end it "emailの正規表現確認" do invalid_addresses = %w[user@example,com user_at_foo.org user.<EMAIL>. <EMAIL> <EMAIL>] invalid_addresses.each do |invalid_address| @user.email = invalid_address expect(@user).not_to be_valid, "#{invalid_address.inspect} should be invalid" end end it "emailが一意でないとNG" do @user = User.new(name: 'Tom', email: '<EMAIL>') duplicate_user = @user.dup # 大文字小文字を区別せずエラーになるか確認 duplicate_user.email = @user.email.upcase @user.save expect(duplicate_user).not_to be_valid end it "emailが小文字で登録されているか確認" do mixed_case_email = "<EMAIL>" @user.email = mixed_case_email @user.save expect(@user.reload.email).to eq(mixed_case_email.downcase) end it "passwordが空だとNG" do @user.password = @user.password_confirmation = " " * 6 expect(@user).not_to be_valid end it "passwordが5文字以下だとNG" do @user.password = @user.password_confirmation = "a" * 5 expect(@user).not_to be_valid end end context 'ユーザー作成の確認' do before do @user1 = create(:user) @user2 = create(:testuser) end it "ユーザーをフォロー&アンフォロー出来ること" do expect(@user1.following?(@user2)).to eq(false) @user1.follow(@user2) expect(@user1.following?(@user2)).to eq(true) expect(@user2.followers.include?(@user1)).to eq(true) @user1.unfollow(@user2) expect(@user1.following?(@user2)).to eq(false) end end context 'feed(microposts)表示の確認' do before do 3.times { create(:user) } @user1 = User.first @user2 = User.second @user3 = User.third @micropost = create(:orange) @micropost = create(:tau_manifesto, user: @user2) @micropost = create(:cat_video, user: @user3) end it "フォローしてるユーザーと自分の投稿のみ表示されること" do @user1.follow(@user2) expect(@user1.following?(@user2)).to eq(true) # フォローしているユーザーの投稿を確認 @user2.microposts.each do |post_following| expect(@user1.feed.include?(post_following)).to eq(true) end # 自分自身の投稿を確認 @user1.microposts.each do |post_self| expect(@user1.feed.include?(post_self)).to eq(true) end # フォローしていないユーザーの投稿を確認 @user3.microposts.each do |post_unfollowed| expect(@user1.feed.include?(post_unfollowed)).to eq(false) end end end end
soichikamiya/sample-app2
spec/system/users_profile_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe 'ユーザープロフィールページ', type: :system do context "プロフィールページ" do # Applicationヘルパーを読み込むと full_titleヘルパー が利用できる include ApplicationHelper before do @user = create(:testuser, name: "SoichiKamiya") 31.times { create(:microposts) } end it 'プロフィールが正しく表示されること' do get user_url(@user) expect(response).to render_template 'users/show' visit user_path(@user) expect(page).to have_title full_title(@user.name) expect(page).to have_selector 'h1', text: @user.name expect(page).to have_selector 'h1>img.gravatar' expect(response.body).to have_content(@user.microposts.count) expect(page).to have_selector 'div.pagination' @user.microposts.paginate(page: 1).each do |micropost| expect(response.body).to have_content(micropost.content) end end end end
soichikamiya/sample-app2
spec/system/users_signup_spec.rb
require 'rails_helper' RSpec.describe 'ユーザー登録', type: :system do context '不正なサインアップ' do it 'nameが空だと登録されない' do expect do post users_url, params: { user: { name: "", email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>" } } end.not_to change(User, :count) expect(response).to have_http_status(200) expect(response).to render_template :new # サーバー処理のため以下の画面(page)確認は出来ない、と思っていたがresponse.bodyでresponse内の画面確認可能 expect(response.body).to have_selector 'div#error_explanation' expect(response.body).to have_selector 'div.alert-danger' end end context '正常なサインアップ(アカウント有効化実施)' do before do # 送信されたメールをクリア ActionMailer::Base.deliveries.clear end it "正しい値だと登録される" do expect do post users_url, params: { user: { name: "testuser", email: "<EMAIL>", password: "<PASSWORD>", password_confirmation: "<PASSWORD>" } } end.to change(User, :count).by(1) # メール内容確認 user = assigns(:user) #UsersController/createの@userを取得 expect(response).to have_http_status(302) expect(ActionMailer::Base.deliveries.size).to eq(1) expect(ActionMailer::Base.deliveries[0].from).to eq(["<EMAIL>"]) expect(ActionMailer::Base.deliveries[0].body.encoded).to match(CGI.escape(user.email)) # rspecだと user.activation_token が呼べなかったので再度 create_activation_digest を実行(privateメソッドなので直書き) user.activation_token = User.new_token user.update_attribute(:activation_digest, User.digest(user.activation_token)) expect(user.activated?).to eq(false) # 有効化していない状態でログインしてみる post login_url, params: { session: { email: user.email, password: "<PASSWORD>" } } expect(session[:user_id]).to eq(nil) # 有効化トークンが不正な場合 get edit_account_activation_path("invalid token", email: user.email) expect(session[:user_id]).to eq(nil) expect(flash[:danger]).to eq("Invalid activation link") # トークンは正しいがメールアドレスが無効な場合 get edit_account_activation_path(user.activation_token, email: "<EMAIL>") expect(session[:user_id]).to eq(nil) expect(flash[:danger]).to be_present # 有効化トークンが正しい場合 get edit_account_activation_path(user.activation_token, email: user.email) # 対応するアクション内のインスタンス変数にアクセス可能(AccountActivationsController/editの@user) user = assigns(:user) #これでactivatedがtrueになっているuserを呼び出せる expect(response).to have_http_status(302) expect(user.activated?).to eq(true) expect(session[:user_id]).to eq(user.id) expect(response).to redirect_to user expect(flash[:success]).to be_present # expect(page).to have_selector 'div.alert-success' #サーバー側の為pageの確認は不可 end end end
soichikamiya/sample-app2
spec/system/password_resets_spec.rb
require 'rails_helper' RSpec.describe 'パスワード再設定', type: :system do describe 'reset_password' do let(:mail) { UserMailer.password_reset(@user) } before do ActionMailer::Base.deliveries.clear @user = create(:testuser, name: "SoichiKamiya") @user.reset_token = User.new_token # URLのhostパラメーターを設定。config/environments/test.rbで指定した為不要 # host = '985b960af22941169449f5a59b363c0c.vfs.cloud9.ap-northeast-1.amazonaws.com' # Rails.application.routes.default_url_options[:host] = host end it "再設定の各種設定確認" do get new_password_reset_url expect(response).to have_http_status(200) # メールアドレスが無効 post password_resets_path, params: { password_reset: { email: "" } } expect(flash[:danger]).to eq("Email address not found") expect(post password_resets_path, params: { password_reset: { email: "" } }).to render_template("password_resets/new") # メールアドレスが有効 post password_resets_path, params: { password_reset: { email: @user.email } } expect(@user.reset_digest).not_to eq(@user.reload.reset_digest) expect(ActionMailer::Base.deliveries.size).to eq(1) expect(ActionMailer::Base.deliveries[0].from).to eq(["<EMAIL>"]) expect(ActionMailer::Base.deliveries[0].body.encoded).to match(CGI.escape(@user.email)) expect(flash[:info]).to eq("Email sent with password reset instructions") expect(response).to redirect_to root_url # パスワード再設定フォームのテスト user = assigns(:user) # メールアドレスが無効 get edit_password_reset_path(user.reset_token, email: "") expect(response).to redirect_to root_url # 無効なユーザー user.toggle!(:activated) get edit_password_reset_path(user.reset_token, email: user.email) expect(response).to redirect_to root_url user.toggle!(:activated) # メールアドレスが有効で、トークンが無効 get edit_password_reset_path('wrong token', email: user.email) expect(response).to redirect_to root_url # メールアドレスもトークンも有効 get edit_password_reset_path(user.reset_token, email: user.email) expect(response).to render_template("password_resets/edit") # expect(page).to have_selector "input[name=email][type=hidden][value=#{user.email}]" expect(user).to eq(assigns(:user)) # 無効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "<PASSWORD>", password_confirmation: "<PASSWORD>" } } @user = assigns(:user) expect(@user.errors.messages[:password_confirmation]).to eq(["doesn't match Password"]) expect(response).to render_template :edit # パスワードが空 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "", password_confirmation: "" } } @user = assigns(:user) expect(@user.errors.messages[:password]).to eq(["can't be blank"]) expect(response).to render_template :edit # 有効なパスワードとパスワード確認 patch password_reset_path(user.reset_token), params: { email: user.email, user: { password: "<PASSWORD>", password_confirmation: "<PASSWORD>" } } expect(session[:user_id]).to eq(user.id) expect(user.reset_digest).not_to eq(user.reload.reset_digest) expect(user.reset_digest).to eq(nil) expect(flash[:success]).to eq("Password has been reset.") expect(response).to redirect_to user end it "期限切れのパスワード再設定" do get new_password_reset_url expect(response).to have_http_status(200) post password_resets_path, params: { password_reset: { email: @user.email } } expect(response).to have_http_status(302) @user = assigns(:user) @user.update_attribute(:reset_sent_at, 3.hours.ago) patch password_reset_path(@user.reset_token), params: { email: @user.email, user: { password: "<PASSWORD>", password_confirmation: "<PASSWORD>" } } expect(response).to have_http_status(302) expect(response).to redirect_to new_password_reset_url expect(flash[:danger]).to eq("Password reset has expired.") end end end
soichikamiya/sample-app2
spec/controllers/sessions_controller_spec.rb
require 'rails_helper' RSpec.describe SessionsController, type: :controller do describe "GET #new" do it "returns http success" do get :new expect(response).to have_http_status(:success) end end describe "remember_meの確認" do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") end it "チェックが無い場合永続保存されないこと" do post :create, params: { session: { email: "<EMAIL>", password: "password", remember_me: 0 } } expect(response).to have_http_status(302) expect(session[:user_id]).to eq(@user.id) expect(@user.remember_digest).to eq(nil) expect(cookies.permanent.signed[:user_id]).to eq(nil) expect(cookies.permanent[:remember_token]).to eq(nil) expect(@user.authenticated?(:remember, cookies[:remember_token])).to eq(false) end it "チェックが有る場合永続保存されること" do post :create, params: { session: { email: "<EMAIL>", password: "password", remember_me: 1 } } expect(response).to have_http_status(302) expect(session[:user_id]).to eq(@user.id) # 何故か session_helper 内の user.remember が効かない為読み込み @user.remember # 改めて cookies[:remember_token]を更新 cookies.permanent[:remember_token] = @user.remember_token expect(@user.remember_digest).not_to eq(nil) # cookies[:user_id]だと暗号化されたままで、下記だと複合化で確認可能 expect(cookies.permanent.signed[:user_id]).to eq(@user.id) expect(cookies.permanent[:remember_token]).not_to eq(nil) expect(@user.authenticated?(:remember, cookies[:remember_token])).to eq(true) end end end
soichikamiya/sample-app2
spec/helpers/sessions_helper_spec.rb
<gh_stars>0 require 'rails_helper' RSpec.describe SessionsHelper, type: :helper do describe "SessionsHelper内の確認" do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") end it "ログインしていない場合current_userがnilであること" do log_out expect(logged_in?).to eq(false) expect(current_user).to eq(nil) expect(response).to have_http_status(200) end it "チェックが有る場合永続保存されること" do # 通常ログイン log_in(@user) expect(response).to have_http_status(200) expect(logged_in?).to eq(true) expect(current_user).to eq(@user) expect(session[:user_id]).to eq(@user.id) expect(cookies.permanent.signed[:user_id]).to eq(nil) expect(cookies.permanent[:remember_token]).to eq(nil) # 一度session[user_id]をdeleteし、current_userのcookies.signed[:user_id]を通るようlogout log_out # 永続ログイン remember(@user) expect(response).to have_http_status(200) expect(logged_in?).to eq(true) expect(current_user).to eq(@user) expect(session[:user_id]).to eq(@user.id) expect(cookies.permanent.signed[:user_id]).to eq(@user.id) expect(cookies.permanent[:remember_token]).not_to eq(nil) expect(@user.authenticated?(:remember, cookies[:remember_token])).to eq(true) end end end
soichikamiya/sample-app2
spec/feature_spec.rb
<gh_stars>0 # require 'rails_helper' # RSpec.describe '静的ページ確認', type: :feature do # describe '各画面の表示確認' do # let(:url_root) { visit root_url } # let(:home_url) { visit static_pages_home_url } # let(:help_url) { visit static_pages_help_url } # let(:about_url) { visit static_pages_about_url } # before do # @base_title = "Ruby on Rails Tutorial Sample App" # end # # js: trueは不可なので chrome開いたりエラーの際Screenshotは無し # shared_examples_for '画面に Ruby on Rails が表示されている' do # it { expect(page).to have_content "Ruby on Rails" } # end # context 'ルートURLの時' do # before do # url_root # end # # shared_examples_for から呼び出し # it_behaves_like '画面に Ruby on Rails が表示されている' # it 'タイトルが正常に表示されている' do # expect(page).to have_title "Home | #{@base_title}" # end # end # context 'ホームURLの時' do # before do # home_url # end # it_behaves_like '画面に Ruby on Rails が表示されている' # it 'タイトルが正常に表示されている' do # expect(page).to have_title "Home | #{@base_title}" # end # end # context 'ヘルプURLの時' do # before do # help_url # end # it_behaves_like '画面に Ruby on Rails が表示されている' # it 'タイトルが正常に表示されている' do # expect(page).to have_title "Help | #{@base_title}" # end # end # context 'アバウトURLの時' do # before do # about_url # end # it_behaves_like '画面に Ruby on Rails が表示されている' # it 'タイトルが正常に表示されている' do # expect(page).to have_title "About | #{@base_title}" # end # end # end # end
soichikamiya/sample-app2
spec/controllers/microposts_controller_spec.rb
require 'rails_helper' RSpec.describe MicropostsController, type: :controller do context "ポストチェック" do before do # @user = create(:testuser) # FactoryBot.create(:testuser)を短縮 buildだとDB登録されない @user = create(:testuser, name: "SoichiKamiya") @micropost = create(:orange) end it "ログインしていない場合 create でリダイレクトされるか" do post :create, params: { micropost: { content: "Lorem ipsum" } } expect(response).to redirect_to login_path end it "ログインしていない場合 destroy リダイレクトされるか" do delete :destroy, params: { id: @micropost.id } expect(response).to redirect_to login_path end end context "別ユーザーのポストを削除しようとするとリダイレクトされるか" do before do 5.times { create(:user) } 5.times { |n| create(:microposts, user: User.find(n+1)) } end it "ログインしていない場合 create でリダイレクトされるか" do # 当ページからログイン出来ない # post login_url, params: { session: { email: "<EMAIL>", password: "<PASSWORD>" } } micropost = Micropost.second expect { delete :destroy, params: { id: micropost.id } }.to change(Micropost, :count).by(0) expect(response).to redirect_to login_path end end end
soichikamiya/sample-app2
spec/controllers/users_controller_spec.rb
require 'rails_helper' RSpec.describe UsersController, type: :controller do describe "GET #new" do it "returns http success" do # get :new get :new expect(response).to have_http_status(:success) end end it "未ログインの場合、ログインページにリダイレクトされること" do get :index expect(response).to have_http_status(302) expect(response).to redirect_to login_path end context 'ログイン有無のフォローリンク確認' do before do @user = create(:user) @user2 = create(:testuser) end it "followingページで未ログインだとレダイレクトされる" do get :following, params: { id: @user.id } expect(response).to redirect_to login_url end it "followersページで未ログインだとレダイレクトされる" do get :followers, params: { id: @user.id } expect(response).to redirect_to login_url end end end
soichikamiya/sample-app2
config/initializers/skip_image_resizing.rb
<reponame>soichikamiya/sample-app2 # /app/uploaders/picture_uploader.rb # include CarrierWave::MiniMagick # process resize_to_limit: [400, 400] # テスト時は画像のリサイズをさせない設定 if Rails.env.test? CarrierWave.configure do |config| config.enable_processing = false end end
soichikamiya/sample-app2
spec/mailers/user_mailer_spec.rb
<filename>spec/mailers/user_mailer_spec.rb require "rails_helper" RSpec.describe UserMailer, type: :mailer do describe "account_activation" do let(:mail) { UserMailer.account_activation(@user) } before do @user = create(:testuser, name: "SoichiKamiya") @user.activation_token = User.new_token # URLのhostパラメーターを設定。config/environments/test.rbで指定した為不要 # host = '985b960af22941169449f5a59b363c0c.vfs.cloud9.ap-northeast-1.amazonaws.com' # Rails.application.routes.default_url_options[:host] = host end it "renders the headers" do expect(mail.subject).to eq("Account activation") expect(mail.to).to eq([@user.email]) expect(mail.from).to eq(["nore<EMAIL>"]) end it "renders the body" do expect(mail.body.encoded).to match("Hi") expect(mail.body.encoded).to match(@user.name) expect(mail.body.encoded).to match(@user.activation_token) expect(mail.body.encoded).to match(CGI.escape(@user.email)) # エンコードされたemail end end describe "password_reset" do let(:mail) { UserMailer.password_reset(@user) } before do @user = create(:testuser, name: "SoichiKamiya") @user.reset_token = User.new_token # URLのhostパラメーターを設定。config/environments/test.rbで指定した為不要 # host = '985b960af22941169449f5a59b363c0c.vfs.cloud9.ap-northeast-1.amazonaws.com' # Rails.application.routes.default_url_options[:host] = host end it "renders the headers" do expect(mail.subject).to eq("Password reset") expect(mail.to).to eq([@user.email]) expect(mail.from).to eq(["<EMAIL>"]) end it "renders the body" do expect(mail.body.encoded).to match(@user.reset_token) expect(mail.body.encoded).to match(CGI.escape(@user.email)) # エンコードされたemail end end end
soichikamiya/sample-app2
config/initializers/carrier_wave.rb
<filename>config/initializers/carrier_wave.rb # 本番環境での画像アップロードを調整する # CarrierWaveを通してS3を使うように修正する # 現時点ではAWSを設定していないので下記は削除 # if Rails.env.production? # CarrierWave.configure do |config| # config.fog_credentials = { # # Amazon S3用の設定 # :provider => 'AWS', # :region => ENV['S3_REGION'], # 例: 東京のリージョン名は 'ap-northeast-1' # :aws_access_key_id => ENV['S3_ACCESS_KEY'], # :aws_secret_access_key => ENV['S3_SECRET_KEY'] # } # config.fog_directory = ENV['S3_BUCKET'] # end # end # 本番環境のメール設定と同じく Herokuの環境変数 ENV を使って、機密情報が漏洩しないようにしてる。 # heroku config:set コマンドを使って、次のようにHeroku上の環境変数を設定が必要。 # ↓ # $ heroku config:set S3_ACCESS_KEY="ココに(AWS IAMユーザーを作成した時の)Accessキーを入力" # $ heroku config:set S3_SECRET_KEY="同様に、Secretキーを入力" # $ heroku config:set S3_BUCKET="Bucketの名前を入力" # $ heroku config:set S3_REGION="Regionの名前を入力"
soichikamiya/sample-app2
spec/factories/microposts.rb
FactoryBot.define do factory :micropost do content { "MyText" } user { nil } end factory :microposts, class: Micropost do # データを生成する毎に通し番号をふってユニークな値を作る sequence(:content) { Faker::Lorem.sentence } sequence(:created_at) { 42.days.ago } sequence(:user) { User.first } end factory :orange, class: Micropost do content { "I just ate an orange!" } user { User.first } created_at { 10.minutes.ago } end factory :tau_manifesto, class: Micropost do content { "Check out the tau_manifesto" } user { User.first } created_at { 3.years.ago } end factory :cat_video, class: Micropost do content { "Sad cats are cat_video" } user { User.first } created_at { 2.hours.ago } end factory :most_recent, class: Micropost do content { "Writing a short test" } user { User.first } created_at { Time.zone.now } end end
soichikamiya/sample-app2
app/controllers/relationships_controller.rb
<gh_stars>0 class RelationshipsController < ApplicationController before_action :logged_in_user def create @user = User.find(params[:followed_id]) # follow.htmlで事前に current_user.active_relationships.build により # current_user の followed(following) を作成する準備(配列作成)をしていたので、 # following << user でuserへのfollowが完成する current_user.follow(@user) # redirect_to user #ajaxを使う為下記のrespond_toメソッドを使用 respond_to do |format| # 順に実行する逐次処理ではなく、リクエストの種類によって応答を場合分けをする (if文の分岐処理に似てる) format.html { redirect_to @user } format.js end end def destroy # unfollow.htmlで current_user.active_relationships.find_by(followed_id: @user.id) により # current_userが@userをフォローしているRelationshipテーブル(id)をパラメーターとして渡し、それを削除する @user = Relationship.find(params[:id]).followed current_user.unfollow(@user) # redirect_to user #ajaxを使う為下記のrespond_toメソッドを使用 respond_to do |format| format.html { redirect_to @user } format.js end end end
soichikamiya/sample-app2
spec/factories/relationships.rb
FactoryBot.define do factory :relationship do follower_id { 1 } followed_id { 2 } end factory :relationship1, class: Relationship do follower { User.first } followed { User.third } end factory :relationship2, class: Relationship do follower_id { 2 } followed_id { 1 } end factory :relationship3, class: Relationship do follower_id { 3 } followed_id { 1 } end end
soichikamiya/sample-app2
app/helpers/microposts_helper.rb
<filename>app/helpers/microposts_helper.rb module MicropostsHelper # def time_ago_in_words(created_at) # Time.zone.now.to_date - created_at.to_date # end end
lpassamano/gradebook
app/models/course.rb
class Course < ActiveRecord::Base belongs_to :instructor, class_name: "User", foreign_key: "instructor_id" has_many :user_courses has_many :users, through: :user_courses has_many :assessments extend Slugifiable::ClassMethods include Slugifiable::InstanceMethods end
lpassamano/gradebook
db/migrate/20170929153222_create_grades.rb
<reponame>lpassamano/gradebook class CreateGrades < ActiveRecord::Migration[5.1] def change create_table :grades do |t| t.string :score t.string :comment t.integer :assessment_id t.integer :student_id end end end
lpassamano/gradebook
app/models/grade.rb
<filename>app/models/grade.rb class Grade < ActiveRecord::Base belongs_to :assessment belongs_to :user end
lpassamano/gradebook
spec/01_models_spec.rb
<reponame>lpassamano/gradebook require 'spec_helper' describe User do before do @user = User.create(name: "test", email: "<EMAIL>", password: "<PASSWORD>") end it "is instantiated with a name, email, and password" do expect(@user.name).to eq("test") expect(@user.email).to eq("<EMAIL>") expect(@user.password).to eq("<PASSWORD>") end it 'has a secure password' do expect(@user.authenticate("test")).to eq(false) expect(@user.authenticate("<PASSWORD>")).to eq(@user) end end describe Course do before do @course = Course.create(name: "Test Class") end it 'is instantiated with a name' do expect(@course.name).to eq("Test Class") end #slugifiable end describe Assessment do before do @assessment = Assessment.create(name: "Final Exam") end it 'is instantiated with a name' do expect(@assessment.name).to eq("Final Exam") end end describe Grade do before do @grade = Grade.create(score: "100", comment: "great job!") end it 'is instantiated with a name and comment' do expect(@grade.score).to eq("100") expect(@grade.comment).to eq("great job!") end end
lpassamano/gradebook
db/migrate/20171005010608_add_default_value_to_grades.rb
<filename>db/migrate/20171005010608_add_default_value_to_grades.rb class AddDefaultValueToGrades < ActiveRecord::Migration[5.1] def change change_column :grades, :score, :string, :default => "-" end end
lpassamano/gradebook
db/migrate/20170929022445_create_instructor_students.rb
class CreateInstructorStudents < ActiveRecord::Migration[5.1] def change create_table :instructor_students do |t| t.integer :instructor_id t.integer :student_id end end end
lpassamano/gradebook
app/models/assessment.rb
class Assessment < ActiveRecord::Base belongs_to :course has_many :grades has_many :users, through: :grades end
lpassamano/gradebook
spec/04_course_features_spec.rb
require 'spec_helper' describe "Course Features" do describe "Courses Index" do before do @student = Role.create(name: "Student") @instructor = Role.create(name: "Instructor") @user = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") @user.role = @instructor course1 = Course.create(name: "Physics 115") course2 = Course.create(name: "Art History 101") @user.courses. << [course1, course2] @user.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params end it 'shows all courses associated with the current user' do get '/courses' expect(last_response.body).to include("Physics 115") expect(last_response.body).to include("Art History 101") end it "has a link to each course's show page" do get '/courses' expect(last_response.body).to include("<a href=\"/courses") end it 'has a link to add a new course if the user is an instructor' do get '/courses' expect(last_response.body).to include("<a href=\"/courses/new\"") end it 'does not have a link to add a new course if the user is a student ' do get '/logout' student = User.new(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") student.role = Role.find_or_create_by(name: "Student") student.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get '/courses' expect(last_response.body).not_to include("Add New Course") end it 'can only be viewed if logged in' do get '/logout' get '/courses/new' expect(last_response.location).to include("/") end end describe "New Course Form" do before do Role.find_or_create_by(name: "Student") Role.find_or_create_by(name: "Instructor") user = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") user.role = Role.find_by(name: "Instructor") user.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params end it 'has a form to add a new course' do Role.find_or_create_by(name: "Instructor") user = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") user.role = Role.find_by(name: "Instructor") user.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get '/courses/new' expect(last_response.body).to include("<form") end it 'has fields for entering course name and up to 15 students' do get '/courses/new' expect(last_response.body).to include("course[name]") expect(last_response.body).to include("15") end it 'redirects to the show page for the new course after the form is submitted' do course = Course.create(name: "Philosophy 101") params = {name: "Philosophy 101"} post '/courses', params expect(last_response.body).to include("Philosophy 101") end it 'creates a new instance of user with a role of student for each student entered into the roster' do params = { :course => { :name => "Beginner Painting", :students => [ { :name => "Juila", :email => "<EMAIL>" }, { :name => "Gil", :email => "<EMAIL>" }, { :name => "Serge", :email => "<EMAIL>" } ] } } post '/courses', params course = Course.find_by(name: "Beginner Painting") #binding.pry roles = course.users.collect { |user| user.role.name } expect(roles.count("Student")).to eq(3) end it 'can only be viewed if logged in' do get '/logout' get '/courses/new' expect(last_response.location).to include("/") end it 'does not allow student users to view the form' do get '/logout' student = User.create(email: "<EMAIL>", password: "<PASSWORD>") student.role = Role.find_or_create_by(name: "Student") student.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get '/courses/new' expect(last_response.location).to include("/courses") end end describe "Course Show Page" do before do instructor = Role.find_or_create_by(name: "Instructor") student = Role.find_or_create_by(name: "Student") user = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") user.role = instructor user.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params @course = Course.create(name: "Photography") becky = User.create(name: "Becky", email: "<EMAIL>", password: "<PASSWORD>") becky.role = student becky.save chaz = User.create(name: "Chaz", email: "<EMAIL>", password: "<PASSWORD>") chaz.role = student chaz.save report = Assessment.create(name: "Report") essay = Assessment.create(name: "Essay") exam = Assessment.create(name: "Final Exam") @course.users << [becky, chaz, user] @course.assessments << [report, essay, exam] @course.save becky_report = Grade.create(score: "75") becky_essay = Grade.create(score: "80") becky_exam = Grade.create(score: "50") chaz_report = Grade.create(score: "79") chaz_essay = Grade.create(score: "55") chaz_exam = Grade.create(score: "105") report.grades << [becky_report, chaz_report] report.save essay.grades << [becky_essay, chaz_essay] essay.save exam.grades << [becky_exam, chaz_exam] exam.save becky.grades << [becky_exam, becky_report, becky_essay] becky.save chaz.grades << [chaz_exam, chaz_report, chaz_essay] chaz.save end it 'displays the course name, student roster, assigments, and student grades' do params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get "/courses/#{@course.slug}" expect(last_response.body).to include("Photography") expect(last_response.body).to include("Becky") expect(last_response.body).to include("Essay") expect(last_response.body).to include("80") end it 'can only be viewed when logged in' do get '/logout' get "/courses/#{@course.slug}" expect(last_response.location).to include("/") end it 'has a link to edit the course information' do params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get "/courses/#{@course.slug}" expect(last_response.body).to include("<a href=\"/courses/#{@course.slug}/edit\"") end it 'has a link to add assessment form' do params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get "/courses/#{@course.slug}" expect(last_response.body).to include("<a href=\"/courses/#{@course.slug}/new\"") end it 'has a link for each existing assessment to individual assessment show page' do get "/courses/#{@course.slug}" expect(last_response.body).to include("<a href=\"/courses/#{@course.slug}/#{@course.assessments.first.slug}\"") end it 'course show page for student users only displays their grades' do params = {email: "<EMAIL>", password: "<PASSWORD>"} get '/logout' post '/login', params get "/courses/#{@course.slug}" expect(last_response.body).not_to include("Becky") expect(last_response.body).not_to include("80") expect(last_response.body).to include("Photography") expect(last_response.body).to include("Report") expect(last_response.body).to include("79") end it 'only users associated with the course can view the course show page' do new_student = User.create(name: "Gil", email: "<EMAIL>", password: "<PASSWORD>") new_student.role = Role.find_or_create_by(name: "Student") new_instructor = User.create(name: "Serge", email: "<EMAIL>", password: "<PASSWORD>") new_instructor. role = Role.find_or_create_by(name: "Instructor") get '/logout' post '/login', params = {email: "<EMAIL>", password: "<PASSWORD>"} get "/courses/#{@course.slug}" expect(last_response.location).to include("/courses") get '/logout' post '/login', params = {email: "<EMAIL>", password: "<PASSWORD>"} get "/courses/#{@course.slug}" expect(last_response.location).to include("/courses") end end describe "Edit Course Form" do before do instructor = Role.find_or_create_by(name: "Instructor") student = Role.find_or_create_by(name: "Student") user = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") user.role = instructor user.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params @course = Course.create(name: "Photography") becky = User.create(name: "Becky", email: "<EMAIL>", password: "<PASSWORD>") becky.role = student becky.save chaz = User.create(name: "Chaz", email: "<EMAIL>", password: "<PASSWORD>") chaz.role = student chaz.save report = Assessment.create(name: "Report") essay = Assessment.create(name: "Essay") exam = Assessment.create(name: "Final Exam") @course.users << [becky, chaz, user] @course.assessments << [report, essay, exam] @course.save becky_report = Grade.create(score: "75") becky_essay = Grade.create(score: "80") becky_exam = Grade.create(score: "50") chaz_report = Grade.create(score: "79") chaz_essay = Grade.create(score: "55") chaz_exam = Grade.create(score: "105") report.grades << [becky_report, chaz_report] report.save essay.grades << [becky_essay, chaz_essay] essay.save exam.grades << [becky_exam, chaz_exam] exam.save becky.grades << [becky_exam, becky_report, becky_essay] becky.save chaz.grades << [chaz_exam, chaz_report, chaz_essay] chaz.save end it 'allows user to change name of course' do ## could not get this test to work ## #params = {course: {name: "Photography - New Name"}} #post "/courses/#{@course.slug}", params #get "/courses/#{@course.slug}" #expect(last_response.body).to include("Photography - New Name") end it 'allows user to add and remove students' do chaz_id = User.find_by(name: "Chaz").id params = { course: { name: "Photography", user_ids: [ chaz_id ], students: [ { name: "Gil", email: "<EMAIL>" } ] } } post "/courses/#{@course.slug}", params get "/courses/#{@course.slug}" expect(@course.users.count).to eq(2) end it 'does not list the instructor in the roster' do get "/courses/#{@course.slug}/edit" expect(last_response.body).not_to include("Leigh") end it 'allows user to add and remove assessments' do params = { course: { name: "Photography", user_ids: [ 2, 3 ], students: [], assessment_ids: [ 1 ], assessments: [ name: "Dark Room Quiz" ] } } post "/courses/#{@course.slug}", params expect(@course.assessments.count).to eq(2) end it 'allows user to delete the course' do get "/courses/#{@course.slug}/edit" expect(last_response.body).to include("Delete Course") end it 'is not visible to student users' do get '/logout' student = User.create(email: "<EMAIL>", password: "<PASSWORD>") student.role = Role.find_or_create_by(name: "Student") student.save params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get "/courses/#{@course.slug}/edit" expect(last_response.location).to include("/") end end end
lpassamano/gradebook
db/seeds.rb
<gh_stars>0 instructor = Role.create(name: "Instructor") student = Role.create(name: "Student") chaz = User.create(name: "Chaz", email: "<EMAIL>", password: "<PASSWORD>") serge = User.create(name: "Serge", email: "<EMAIL>", password: "<PASSWORD>") jessie = User.create(name: "Jessie", email: "<EMAIL>", password: "<PASSWORD>") instructor.users << [chaz, serge, jessie] leigh = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") gil = User.create(name: "Gil", email: "<EMAIL>", password: "<PASSWORD>") obi = User.create(name: "Obi", email: "<EMAIL>", password: "<PASSWORD>") brian = User.create(name: "Brian", email: "<EMAIL>", password: "<PASSWORD>") ww = User.create(name: "<NAME>", email: "<EMAIL>", password: "<NAME>") marty = User.create(name: "<NAME>", email: "<EMAIL>", password: "<NAME>") harry = User.create(name: "<NAME>", email: "<EMAIL>", password: "<NAME>") ron = User.create(name: "<NAME>", email: "<EMAIL>", password: "<NAME>") hermoine = User.create(name: "<NAME>", email: "<EMAIL>", password: "<NAME>") student.users << [leigh, gil, obi, brian, ww, marty, harry, ron, hermoine] physics = Course.create(name: "Physics 101") food = Course.create(name: "Food Appreciation") astro = Course.create(name: "Intro to Astronomy") pl = Course.create(name: "Powerlifting") physics.users << [chaz, leigh, gil, obi, ww, hermoine] food.users << [serge, leigh, gil, obi, brian, ron, harry, hermoine] astro.users << [jessie, obi, gil, ww, marty, hermoine] pl.users << [jessie, obi, gil, ww, harry, ron] physics_assessments = [ "Lab 1", "Lab 2", "Lab 3", "Lab 4", "Lab 5", "Midterm Exam", "Group Project", "Final Exam" ] physics_assessments.each do |assessment| a = Assessment.create(name: assessment) physics.assessments << a physics.save end physics_roster = [leigh, gil, obi, ww, hermoine] physics_roster.each do |student| physics.assessments.each do |assessment| g = Grade.create student.grades << g assessment.grades << g student.save assessment.save end end
lpassamano/gradebook
db/migrate/20170929014530_create_course_students.rb
class CreateCourseStudents < ActiveRecord::Migration[5.1] def change create_table :course_students do |t| t.integer :course_id t.integer :student_id end end end
lpassamano/gradebook
db/migrate/20170930214659_edit_assessements.rb
class EditAssessements < ActiveRecord::Migration[5.1] def change remove_column :assessments, :grade remove_column :assessments, :comment remove_column :assessments, :student_id end end
lpassamano/gradebook
spec/03_controllers_spec.rb
<reponame>lpassamano/gradebook require 'spec_helper' describe ApplicationController do describe "Homepage" do it 'loads the homepage' do get '/' expect(last_response.status).to eq(200) expect(last_response.body).to include("Welcome!") end it 'has links to login or signup' do get '/' expect(last_response.body).to include("Login") expect(last_response.body).to include("Signup") end end describe "Signup" do before do Role.find_or_create_by(name: "Student") Role.find_or_create_by(name: "Instructor") end it 'loads the signup page' do get '/signup' do expect(last_response.status).to eq(200) end end it 'does not let a user sign up without a name, email, and password' do params = {name: "", email: "<EMAIL>", password: "<PASSWORD>"} post '/signup', params expect(last_response.location).to include('/signup') end it 'has option to choose to sign up as a student or instructor' do get '/signup' expect(last_response.body).to include("<input type=\"radio\" value=\"#{Role.find_by(name: "Instructor").id}\"") expect(last_response.body).to include("<input type=\"radio\" value=\"#{Role.find_by(name: "Student").id}\"") end it 'redirects you to courses index' do params = {name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>", role_id: "2"} post '/signup', params expect(last_response.location).to include("/courses") end it 'creates a user with a role' do Role.find_or_create_by(name: "Student") Role.find_or_create_by(name: "Instructor") #params = {name: "<NAME>", email: "<EMAIL>", password: "<PASSWORD>"} visit '/signup' fill_in :name, :with => "<NAME>" fill_in :email, :with => "<EMAIL>" fill_in :password, :with => "<PASSWORD>" page.choose 'role_2' click_button 'submit' expect(User.find_by(name: "<NAME>").role.id).to eq(2) end end describe "Login" do before do @user = User.create(name: "Charles", email: "<EMAIL>", password: "<PASSWORD>") end it 'loads the login page' do get '/login' expect(last_response.status).to eq(200) end it 'redirects to course index after login' do params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params expect(last_response.location).to include("/courses") end it 'does not allow you to login with an incorrect password' do params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params expect(last_response.location).to include("/login") end it 'does not allow you to login with an unregistered email' do params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params expect(last_response.location).to include("/login") end end describe "Logout" do it 'lets an user log out if they are logged in' do user = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") params = {email: "<EMAIL>", password: "<PASSWORD>"} post '/login', params get '/logout' expect(last_response.location).to include("/") end end end #tests to add when building out the student features # student cannot access the add/edit course forms # student does not see any links to edit/add forms
lpassamano/gradebook
config.ru
require_relative './config/environment' use Rack::MethodOverride use UserController use CoursesController run ApplicationController
lpassamano/gradebook
spec/02_associations_spec.rb
require 'spec_helper' describe 'User Associations' do before do @user = User.create(name: "Charles", email: "<EMAIL>", password: "<PASSWORD>") end it 'has many courses' do math = Course.create(name: "Math") chem = Course.create(name: "Chemistry") @user.courses << [math, chem] @user.save expect(User.find_by(name: "Charles").courses.count).to eq(2) end it 'belongs to a role' do role = Role.create(name: "Instructor") @user.role = role @user.save expect(User.find_by(name: "Charles").role).to eq(role) end it 'has many grades' do exam = Grade.create(score: "95") project = Grade.create(score: "50") @user.grades << [exam, project] expect(User.find_by(name: "Charles").grades.count).to eq(2) end end describe 'Course Associations' do before do @course = Course.create(name: "Test Course") end it 'has many users' do leigh = User.create(name: "Leigh", email: "<EMAIL>", password: "<PASSWORD>") becky = User.create(name: "Becky", email: "<EMAIL>", password: "<PASSWORD>") @course.users << [leigh, becky] @course.save expect(Course.find_by(name: "Test Course").users.count).to eq(2) end it 'has many assessments' do report = Assessment.create(name: "Report") essay = Assessment.create(name: "Essay") exam = Assessment.create(name: "Final Exam") @course.assessments << [report, essay, exam] @course.save expect(Course.find_by(name: "Test Course").assessments.include?(exam)).to eq(true) end end describe 'Assessment Associations' do before do @assessment = Assessment.create(name: "Book Report") end it 'belongs to an course' do physics = Course.create(name: "Physics") @assessment.course = physics @assessment.save expect(Assessment.find_by(name: "Book Report").course).to eq(physics) end it 'has many grades' do x = Grade.create y = Grade.create z = Grade.create @assessment.grades << [x, y, z] @assessment.save expect(Assessment.find_by(name: "Book Report").grades.count).to eq(3) end end describe "Grade Associations" do before do @grade = Grade.create(score: "100") end it 'belongs to a user' do leigh = User.create(name: "Leigh", password: "<PASSWORD>") @grade.user = leigh @grade.save expect(Grade.find_by(score: "100").user).to eq(leigh) end it 'belongs to an assessment' do exam = Assessment.create @grade.assessment = exam @grade.save expect(Grade.find_by(score: "100").assessment).to eq(exam) end end
lpassamano/gradebook
db/migrate/20170930214536_drop_instructor_students.rb
<filename>db/migrate/20170930214536_drop_instructor_students.rb class DropInstructorStudents < ActiveRecord::Migration[5.1] def change drop_table :instructor_students end end
lpassamano/gradebook
app/controllers/courses_controller.rb
class CoursesController < ApplicationController get '/courses' do redirect '/' if !logged_in? @user = current_user erb :"courses/index" end get '/courses/new' do if !logged_in? redirect '/' elsif current_user.instructor? erb :"courses/new" else redirect '/courses' end end post '/courses' do course = Course.create(params[:course]) populate_course(params, course) redirect "/courses/#{course.slug}" end get '/courses/register' do redirect '/' if !logged_in? if current_user.student? erb :"courses/register" else redirect "/courses" end end post '/courses/register' do current_user.update(params) redirect "/courses" end get '/courses/:slug' do redirect '/' if !logged_in? @course = Course.find_by_slug(params[:slug]) if current_user.instructor? && current_user.courses.include?(@course) sort_assessments_and_grades(@course) erb :"courses/show" elsif current_user.student? && current_user.courses.include?(@course) erb :"courses/show_student_user" else redirect "/courses" end end get '/courses/:slug/edit' do @course = Course.find_by_slug(params[:slug]) if !logged_in? redirect '/' elsif current_user.instructor? && current_user.courses.include?(@course) erb :"courses/edit" else redirect '/courses' end end post '/courses/:slug' do course = Course.find_by_slug(params[:slug]) delete_removed_assessments_grades(params[:course], course) course.update(params[:course]) populate_course(params, course) redirect "/courses/#{course.slug}" end get '/courses/:slug/grades' do @course = Course.find_by_slug(params[:slug]) if !logged_in? redirect "/" elsif current_user.instructor? && current_user.courses.include?(@course) sort_assessments_and_grades(@course) erb :"courses/grades" else redirect "/courses" end end post '/courses/:slug/grades' do course = Course.find_by_slug(params[:slug]) params[:grade_ids].each do |key, value| grade = Grade.find(key.to_i) grade.update(value) end redirect "/courses/#{course.slug}" end delete '/courses/:slug/delete' do @course = Course.find_by_slug(params[:slug]) if !logged_in? redirect "/" elsif current_user.instructor? && current_user.courses.include?(@course) @course.delete erb :"courses/delete" else redirect "/courses" end end helpers do def populate_course(params, course) find_or_create_student_users(params[:users], course) create_assessments(params[:assessments], course) create_grades(course) end def find_or_create_student_users(users, course) users.each do |user| if user[:name] != "" && user[:email] != "" if u = User.find_by(email: user[:email]) course.users << u if u.student? else u = User.new(user) u.password = <PASSWORD> u.save course.users << u end end end end def create_assessments(assessments, course) assessments.each do |assessment| if assessment[:name] != "" a = Assessment.create(assessment) course.assessments << a end end end def create_grades(course) course.assessments.each do |assessment| course.users.each do |user| if user.student? && user.assessment_ids.exclude?(assessment.id) grade = Grade.create user.grades << grade assessment.grades << grade end end end end def sort_assessments_and_grades(course) course.assessments.sort_by {|assessment| assessment.id} course.users.each do |user| if user.student? user.grades.sort_by {|grade| grade.assessment_id} end end end def delete_removed_assessments_grades(assessments, course) course.users.each do |user| if user.student? user.grades.each do |grade| grade.delete if removed_assessments(assessments, course).include?(grade.assessment_id) end end end end def removed_assessments(assessments, course) if assessments[:assessment_ids] == nil @removed_assessments ||= course.assessment_ids else @removed_assessments ||= course.assessment_ids.find_all do |id| assessments[:assessment_ids].exclude?(id.to_s) end end end end end
lpassamano/gradebook
app/controllers/user_controller.rb
<gh_stars>0 require 'rack-flash' class UserController < ApplicationController use Rack::Flash get '/signup' do if logged_in? redirect "/courses" else @roles = Role.all erb :"user/signup" end end post '/signup' do ## if user = User.find_by(email: params[:email]) if user.student? && user.authenticate(user.name) #if password == name then student was created in the new/edit course form and does not have an account user.password = params[:password] session[:user_id] = user.id # let them know they already have an acccount and have them set new password redirect "/courses" else flash[:message] = "Account already created with this email. Please login to access Gradebook." # don't redirect to login redirect "/login" end else user = User.new(params) if !!params[:role_id] && params[:name] != "" && params[:email] != "" && user.save session[:user_id] = user.id redirect "/courses" else flash[:message] = "Please enter name, email, password, and account type to signup for Gradebook." redirect "/signup" end end end get '/login' do if logged_in? redirect "/courses" else erb :"user/login" end end post '/login' do user = User.find_by(email: params[:email]) if user && user.authenticate(params[:password]) session[:user_id] = user.id redirect "/courses" else flash[:message] = "Incorrect email and/or password. Please try to login again or signup for a new account." redirect "/" end end get '/logout' do session.clear if logged_in? redirect "/" end end
lpassamano/gradebook
app/models/user.rb
class User < ActiveRecord::Base has_secure_password belongs_to :role has_many :user_courses has_many :courses, through: :user_courses has_many :grades has_many :assessments, through: :grades def student? self.role == Role.find_by(name: "Student") end def instructor? self.role == Role.find_by(name: "Instructor") end end
lpassamano/gradebook
db/migrate/20171001201110_delete_students_instructors.rb
class DeleteStudentsInstructors < ActiveRecord::Migration[5.1] def change drop_table :course_students remove_column :courses, :instructor_id remove_column :grades, :student_id drop_table :instructors drop_table :students end end
pjk25/cf-uaa-lib
lib/uaa/util.rb
<filename>lib/uaa/util.rb #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'multi_json' require "base64" require 'logger' require 'uri' # Cloud Foundry namespace module CF # Namespace for User Account and Authentication service module UAA end end class Logger # @private Severity::TRACE = Severity::DEBUG - 1 def trace(progname, &blk); add(Logger::Severity::TRACE, nil, progname, &blk) end def trace? ; @level <= Logger::Severity::TRACE end end module CF::UAA # Useful parent class. All CF::UAA exceptions are derived from this. class UAAError < RuntimeError; end # Indicates an authentication error. class AuthError < UAAError; end # Indicates an error occurred decoding a token, base64 decoding, or JSON. class DecodeError < UAAError; end # Helper functions useful to the UAA client APIs class Util # General method to transform a hash key to a given style. Useful when # dealing with HTTP headers and various protocol tags that tend to contain # '-' characters and are case-insensitive and want to use them as keys in # ruby hashes. Useful for dealing with {http://www.simplecloud.info/ SCIM} # case-insensitive attribute names to normalize all attribute names (downcase). # # @param [String, Symbol] key current key # @param [Symbol] style can be sym, downsym, down, str, [un]dash, [un]camel, nil, none # @return [String, Symbol] new key def self.hash_key(key, style) case style when nil, :none then key when :downsym then key.to_s.downcase.to_sym when :sym then key.to_sym when :str then key.to_s when :down then key.to_s.downcase when :dash then key.to_s.downcase.tr('_', '-') when :undash then key.to_s.downcase.tr('-', '_').to_sym when :uncamel then key.to_s.gsub(/([A-Z])([^A-Z]*)/,'_\1\2').downcase.to_sym when :camel then key.to_s.gsub(/(_[a-z])([^_]*)/) { $1[1].upcase + $2 } else raise ArgumentError, "unknown hash key style: #{style}" end end # Modifies obj in place changing any hash keys to style. Recursively modifies # subordinate hashes. # @param style (see Util.hash_key) # @return modified obj def self.hash_keys!(obj, style = nil) return obj if style == :none return obj.each {|o| hash_keys!(o, style)} if obj.is_a? Array return obj unless obj.is_a? Hash newkeys, nk = {}, nil obj.delete_if { |k, v| hash_keys!(v, style) newkeys[nk] = v unless (nk = hash_key(k, style)) == k nk != k } obj.merge!(newkeys) end # Makes a new copy of obj with hash keys to style. Recursively modifies # subordinate hashes. # @param style (see Util.hash_key) # @return obj or new object if hash keys were changed def self.hash_keys(obj, style = nil) return obj.collect {|o| hash_keys(o, style)} if obj.is_a? Array return obj unless obj.is_a? Hash obj.each_with_object({}) {|(k, v), h| h[hash_key(k, style)] = hash_keys(v, style) } end # handle ruby 1.8.7 compatibility for form encoding if URI.respond_to?(:encode_www_form_component) def self.encode_component(str) URI.encode_www_form_component(str) end #@private def self.decode_component(str) URI.decode_www_form_component(str) end #@private else def self.encode_component(str) # @private str.to_s.gsub(/([^ a-zA-Z0-9*_.-]+)/) { '%' + $1.unpack('H2' * $1.size).join('%').upcase }.tr(' ', '+') end def self.decode_component(str) # @private str.tr('+', ' ').gsub(/((?:%[0-9a-fA-F]{2})+)/) {[$1.delete('%')].pack('H*')} end end # Takes an x-www-form-urlencoded string and returns a hash of utf-8 key/value # pairs. Useful for OAuth parameters. Raises ArgumentError if a key occurs # more than once, which is a restriction of OAuth query strings. # OAuth parameters are case sensitive, scim parameters are case-insensitive. # @see http://tools.ietf.org/html/rfc6749#section-3.1 # @param [String] url_encoded_pairs in an x-www-form-urlencoded string # @param style (see Util.hash_key) # @return [Hash] of key value pairs def self.decode_form(url_encoded_pairs, style = nil) pairs = {} url_encoded_pairs.split(/[&;]/).each do |pair| k, v = pair.split('=', 2).collect { |v| decode_component(v) } raise "duplicate keys in form parameters" if pairs.key?(k = hash_key(k, style)) pairs[k] = v end pairs rescue Exception => e raise ArgumentError, e.message end # Encode an object into x-www-form-urlencoded string suitable for oauth2. # @note that ruby 1.9.3 converts form components to utf-8. Ruby 1.8.7 # users must ensure all data is in utf-8 format before passing to form encode. # @param [Hash] obj a hash of key/value pairs to be encoded. # @see http://tools.ietf.org/html/rfc6749#section-3.1 def self.encode_form(obj) obj.map {|k, v| encode_component(k) << '=' << encode_component(v)}.join('&') end # Converts +obj+ to JSON # @return [String] obj in JSON form. def self.json(obj) MultiJson.dump(obj) end # Converts +obj+ to nicely formatted JSON # @return [String] obj in formatted json def self.json_pretty(obj) MultiJson.dump(obj, :pretty => true) end # Converts +obj+ to a URL-safe base 64 encoded string # @return [String] def self.json_encode64(obj = {}) encode64(json(obj)) end # Decodes base64 encoding of JSON data. # @param [String] str # @param style (see Util.hash_key) # @return [Hash] def self.json_decode64(str, style = nil) json_parse(decode64(str), style) end # Encodes +obj+ as a URL-safe base 64 encoded string, with trailing padding removed. # @return [String] def self.encode64(obj) str = Base64.respond_to?(:urlsafe_encode64)? Base64.urlsafe_encode64(obj): [obj].pack("m").tr("+/", "-_") str.gsub!(/(\n|=*$)/, '') str end # Decodes a URL-safe base 64 encoded string. Adds padding if necessary. # @return [String] decoded string def self.decode64(str) return unless str pad = str.length % 4 str = str + '=' * (4 - pad) if pad > 0 Base64.respond_to?(:urlsafe_decode64) ? Base64.urlsafe_decode64(str) : Base64.decode64(str.tr('-_', '+/')) rescue ArgumentError raise DecodeError, "invalid base64 encoding" end # Parses a JSON string. # @param style (see Util.hash_key) # @return [Hash] parsed data def self.json_parse(str, style = nil) hash_keys!(MultiJson.load(str), style) if str && !str.empty? rescue MultiJson::DecodeError raise DecodeError, "json decoding error" end # Converts obj to a string and truncates if over limit. # @return [String] def self.truncate(obj, limit = 50) return obj.to_s if limit == 0 limit = limit < 5 ? 1 : limit - 4 str = obj.to_s[0..limit] str.length > limit ? str + '...': str end # Converts common input formats into array of strings. # Many parameters in these classes can be given as arrays, or as a list of # arguments separated by spaces or commas. This method handles the possible # inputs and returns an array of strings. # @return [Array<String>] def self.arglist(arg, default_arg = nil) arg = default_arg unless arg return arg if arg.nil? || arg.respond_to?(:join) raise ArgumentError, "arg must be Array or space|comma delimited strings" unless arg.respond_to?(:split) arg.split(/[\s\,]+/).reject { |e| e.empty? } end # Joins arrays of strings into a single string. Reverse of {Util.arglist}. # @param [Object, #join] arg # @param [String] delim delimiter to put between strings. # @return [String] def self.strlist(arg, delim = ' ') arg.respond_to?(:join) ? arg.join(delim) : arg.to_s if arg end # Set the default logger used by the higher level classes. # @param [String, Symbol] level such as info, debug trace. # @param [IO] sink output for log messages, defaults to $stdout # @return [Logger] def self.default_logger(level = nil, sink = nil) if sink || !@default_logger @default_logger = Logger.new(sink || $stdout) level = :info unless level @default_logger.formatter = Proc.new { |severity, time, pname, msg| msg } end @default_logger.level = Logger::Severity.const_get(level.to_s.upcase) if level @default_logger end end end
pjk25/cf-uaa-lib
spec/scim_spec.rb
#-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'spec_helper' require 'uaa/scim' require 'uri' require 'cgi' module CF::UAA describe Scim do let(:options) { {} } before do #Util.default_logger(:trace) @authheader, @target = 'bEareR xyz', 'https://test.target' @scim = Scim.new(@target, @authheader, options) end subject { @scim } def check_headers(headers, content, accept, zone) headers['content-type'].should =~ /application\/json/ if content == :json headers['content-type'].should be_nil unless content headers['accept'].should =~ /application\/json/ if accept == :json headers['accept'].should be_nil unless accept headers['authorization'].should =~ /^(?i:bearer)\s+xyz$/ headers['X-Identity-Zone-Subdomain'].should eq zone end describe 'initialize' do let(:options) { {:http_proxy => 'http-proxy.com', :https_proxy => 'https-proxy.com', :skip_ssl_validation => true} } it 'sets skip_ssl_validation' do subject.skip_ssl_validation == true end end it 'adds an object' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users" method.should == :post check_headers(headers, :json, :json, nil) [200, '{"ID":"id12345"}', {'content-type' => 'application/json'}] end result = subject.add(:user, :hair => 'brown', :shoe_size => 'large', :eye_color => ['blue', 'green'], :name => 'fred') result['id'].should == 'id12345' end it 'gets client meta' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/oauth/clients/id12345/meta" method.should == :get check_headers(headers, nil, :json, nil) [200, '{"id":"id12345", "created_by": "Marissa"}', {'content-type' => 'application/json'}] end result = subject.get_client_meta('id12345') result['id'].should == 'id12345' result['created_by'].should == 'Marissa' end it 'replaces an object' do obj = {:hair => 'black', :shoe_size => 'medium', :eye_color => ['hazel', 'brown'], :name => 'fredrick', :meta => {:version => 'v567'}, :id => 'id12345'} subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users/id12345" method.should == :put check_headers(headers, :json, :json, nil) headers['if-match'].should == 'v567' [200, '{"ID":"id12345"}', {'content-type' => 'application/json'}] end result = subject.put(:user, obj) result['id'].should == 'id12345' end it 'modifies an object' do obj = {:hair => 'black', :shoe_size => 'medium', :eye_color => ['hazel', 'brown'], :name => 'fredrick', :meta => {:version => 'v567'}, :id => 'id12345'} subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users/id12345" method.should == :patch check_headers(headers, :json, :json, nil) headers['if-match'].should == 'v567' [200, '{"ID":"id12345"}', {'content-type' => 'application/json'}] end result = subject.patch(:user, obj) result['id'].should == 'id12345' end it 'gets an object' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users/id12345" method.should == :get check_headers(headers, nil, :json, nil) [200, '{"id":"id12345"}', {'content-type' => 'application/json'}] end result = subject.get(:user, 'id12345') result['id'].should == 'id12345' end it 'pages through all objects' do subject.set_request_handler do |url, method, body, headers| url.should =~ %r{^#{@target}/Users\?} url.should =~ %r{[\?&]attributes=id(&|$)} url.should =~ %r{[\?&]includeInactive=true(&|$)} url.should =~ %r{[\?&]startIndex=[12](&|$)} method.should == :get check_headers(headers, nil, :json, nil) reply = url =~ /startIndex=1/ ? '{"TotalResults":2,"ItemsPerPage":1,"StartIndex":1,"RESOURCES":[{"id":"id12345"}]}' : '{"TotalResults":2,"ItemsPerPage":1,"StartIndex":2,"RESOURCES":[{"id":"id67890"}]}' [200, reply, {'content-type' => 'application/json'}] end result = subject.all_pages(:user, :attributes => 'id', :includeInactive => true) [result[0]['id'], result[1]['id']].to_set.should == ['id12345', 'id67890'].to_set end it "changes a user's password" do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users/id12345/password" method.should == :put check_headers(headers, :json, :json, nil) body.should include('"password":"<PASSWORD>"', '"oldPassword":"<PASSWORD>"') [200, '{"id":"id12345"}', {'content-type' => 'application/json'}] end result = subject.change_password('<PASSWORD>', '<PASSWORD>', '<PASSWORD>') result['id'].should == 'id12345' end it "tries to change the user's password to be the same as the old one" do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users/id12345/password" method.should == :put check_headers(headers, :json, :json, nil) [400, '{"error":"invalid_password","message":"Your new password cannot be the same as the old password."}', {'content-type' => 'application/json'}] end expect {subject.change_password('<PASSWORD>', '<PASSWORD>', '<PASSWORD>')}.to raise_error(error=TargetError) end it "changes a client's secret" do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/oauth/clients/id12345/secret" method.should == :put check_headers(headers, :json, :json, nil) body.should include('"secret":"newpwd"', '"oldSecret":"oldpwd"') [200, '{"id":"id12345"}', {'content-type' => 'application/json'}] end result = subject.change_secret('id12345', 'newpwd', 'oldpwd') result['id'].should == 'id12345' end it 'unlocks a user' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users/id12345/status" method.should == :patch check_headers(headers, :json, :json, nil) body.should include('"locked":false') [200, '{"locked":false}', {'content-type' => 'application/json'}] end result = subject.unlock_user('id12345') result['locked'].should == false end it 'adds a mapping from uaa groups to external group' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Groups/External" method.should == :post check_headers(headers, :json, :json, nil) body.should include('"displayName":"uaa-scope-name"', '"externalGroup":"external-group-name"', '"schemas":["urn:scim:schemas:core:1.0"]', '"origin":"test-origin"') [201, '{"displayName":"uaa-scope-name", "externalGroup": "external-group-name"}', {'content-type' => 'application/json'}] end result = subject.map_group('uaa-scope-name', false, 'external-group-name', 'test-origin') result['displayname'].should == 'uaa-scope-name' result['externalgroup'].should == 'external-group-name' end it 'defaults to ldap origin when mapping a uaa group from an external group' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Groups/External" method.should == :post check_headers(headers, :json, :json, nil) body.should include('"displayName":"uaa-scope-name"', '"externalGroup":"external-group-name"', '"schemas":["urn:scim:schemas:core:1.0"]', '"origin":"ldap"') [201, '{"displayName":"uaa-scope-name", "externalGroup": "external-group-name"}', {'content-type' => 'application/json'}] end result = subject.map_group('uaa-scope-name', false, 'external-group-name') result['displayname'].should == 'uaa-scope-name' result['externalgroup'].should == 'external-group-name' end it 'unmaps a uaa group from an external group' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Groups/External/groupId/uaa-group-id/externalGroup/external%20group%20name/origin/test-origin" method.should == :delete check_headers(headers, nil, nil, nil) [200, '{"displayName":"uaa-scope-name", "groupId": "uaa-group-id", "externalGroup": "external-group-name"}', {'content-type' => 'application/json'}] end subject.unmap_group('uaa-group-id', 'external group name', 'test-origin') end it 'defaults to ldap origin when unmapping a uaa group from an external group' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Groups/External/groupId/uaa-group-id/externalGroup/external%20group%20name/origin/ldap" method.should == :delete check_headers(headers, nil, nil, nil) [200, '{"displayName":"uaa-scope-name", "groupId": "uaa-group-id", "externalGroup": "external-group-name"}', {'content-type' => 'application/json'}] end subject.unmap_group('uaa-group-id', 'external group name') end describe 'users in a zone' do let(:options) { {:http_proxy => 'http-proxy.com', :https_proxy => 'https-proxy.com', :skip_ssl_validation => true, :zone => 'derpzone'} } it 'sends zone header' do subject.set_request_handler do |url, method, body, headers| url.should == "#{@target}/Users" method.should == :post check_headers(headers, :json, :json, 'derpzone') [200, '{"ID":"id12345"}', {'content-type' => 'application/json'}] end result = subject.add(:user, :hair => 'brown', :shoe_size => 'large', :eye_color => ['blue', 'green'], :name => 'fred') result['id'].should == 'id12345' end end describe '#list_group_mappings' do it 'lists all the external group mappings with default pagination' do subject.set_request_handler do |url, method, body, headers| url.should start_with("#{@target}/Groups/External/list") method.should == :get check_headers(headers, nil, :json, nil) [ 200, '{"resources": [{"groupId": "group-id", "displayName": "group-name", "externalGroup": "external-group-name"}], "totalResults": 1 }', {'content-type' => 'application/json'} ] end result = subject.list_group_mappings result['resources'].length.should == 1 result['totalresults'].should == 1 end it 'lists a page of external group mappings starting from an index' do subject.set_request_handler do |url, method, body, headers| url.should start_with("#{@target}/Groups/External/list") method.should == :get check_headers(headers, nil, :json, nil) query_params = CGI::parse(URI.parse(url).query) start_index = query_params['startIndex'].first count = query_params['count'].first start_index.should == '3' count.should == '10' [ 200, '{"resources": [{"groupId": "group-id", "displayName": "group-name", "externalGroup": "external-group-name"}], "totalResults": 1 }', {'content-type' => 'application/json'} ] end subject.list_group_mappings(3, 10) end end end end
pjk25/cf-uaa-lib
spec/token_coder_spec.rb
<gh_stars>0 #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'spec_helper' require 'uaa/token_coder' module CF::UAA describe TokenCoder do subject { TokenCoder.new(:audience_ids => "test_resource", :skey => "test_secret", :pkey => OpenSSL::PKey::RSA.generate(512) ) } before :each do @tkn_body = {'foo' => "bar"} @tkn_secret = "test_secret" end it "raises error if the given auth header is bad" do expect { subject.decode(nil) }.to raise_exception(InvalidTokenFormat) expect { subject.decode("one two three") }.to raise_exception(InvalidTokenFormat) end it "encodes/decodes a token using a symmetrical key" do tkn = subject.encode(@tkn_body, 'HS512') result = subject.decode("bEaReR #{tkn}") result.should_not be_nil result["foo"].should == "bar" end it "encodes/decodes a token using pub/priv key" do tkn = subject.encode(@tkn_body, 'RS256') result = subject.decode("bEaReR #{tkn}") result.should_not be_nil result["foo"].should == "bar" end it "encodes/decodes a token using pub/priv key from PEM" do pem = <<-DATA.gsub(/^ +/, '') -----BEGIN RSA PRIVATE KEY----- <KEY> -----END RSA PRIVATE KEY----- DATA coder = TokenCoder.new(:audience_ids => "test_resource", :pkey => pem) tkn = coder.encode(@tkn_body, 'RS256') result = coder.decode("bEaReR #{tkn}") result.should_not be_nil result["foo"].should == "bar" end it "encodes/decodes with 'none' signature if explicitly accepted" do tkn = subject.encode(@tkn_body, 'none') result = TokenCoder.decode(tkn, :accept_algorithms => "none") result.should_not be_nil result["foo"].should == "bar" end it "rejects a token with 'none' signature by default" do tkn = subject.encode(@tkn_body, 'none') expect { TokenCoder.decode(tkn) }.to raise_exception(SignatureNotAccepted) end it "raises an error if the signing algorithm is not supported" do expect { subject.encode(@tkn_body, 'baz') }.to raise_exception(SignatureNotSupported) end it "raises an error if the token is for another resource server" do tkn = subject.encode({'aud' => ["other_resource"], 'foo' => "bar"}) expect { subject.decode("bEaReR #{tkn}") }.to raise_exception(InvalidAudience) end it "raises an error if the token is signed by an unknown signing key" do other = TokenCoder.new(:audience_ids => "test_resource", :skey => "other_secret") tkn = other.encode(@tkn_body) expect { subject.decode("bEaReR #{tkn}") }.to raise_exception(InvalidSignature) end it "raises an error if the token is public-key signed and we try to decode with symmetric key" do pem = <<-DATA.gsub(/^ +/, '') -----BEGIN RSA PRIVATE KEY----- <KEY>2Q== -----END RSA PRIVATE KEY----- DATA coder = TokenCoder.new(:audience_ids => "test_resource", :pkey => pem) coder2 = TokenCoder.new(:audience_ids => "test_resource", :skey => 'randomness') tkn = coder.encode(@tkn_body, 'RS256') expect { coder2.decode("bEaReR #{tkn}") }.to raise_exception(InvalidSignature) end it "raises an error if the token is symmetric-key signed and we try to decode with a public key" do pem = <<-DATA.gsub(/^ +/, '') -----BEGIN RSA PRIVATE KEY----- <KEY> -----END RSA PRIVATE KEY----- DATA coder = TokenCoder.new(:audience_ids => "test_resource", :pkey => pem) coder2 = TokenCoder.new(:audience_ids => "test_resource", :skey => 'randomness') tkn = coder2.encode(@tkn_body) expect { coder.decode("bEaReR #{tkn}") }.to raise_exception(InvalidSignature) end it "raises an error if the token is an unknown signing algorithm" do segments = [Util.json_encode64(:typ => "JWT", :alg =>"BADALGO")] segments << Util.json_encode64(@tkn_body) segments << Util.encode64("BADSIG") tkn = segments.join('.') tc = TokenCoder.new(:audience_ids => "test_resource", :skey => "test_secret", :pkey => OpenSSL::PKey::RSA.generate(512), :accept_algorithms => "BADALGO") expect { tc.decode("bEaReR #{tkn}") }.to raise_exception(SignatureNotSupported) end it "raises an error if the token is malformed" do tkn = "one.two.three.four" expect { subject.decode("bEaReR #{tkn}") }.to raise_exception(InvalidTokenFormat) tkn = "onlyone" expect { subject.decode("bEaReR #{tkn}") }.to raise_exception(InvalidTokenFormat) end it "raises a decode error if a token segment is malformed" do segments = [Util.encode64("this is not json")] segments << Util.encode64("n/a") segments << Util.encode64("n/a") tkn = segments.join('.') expect { subject.decode("bEaReR #{tkn}") }.to raise_exception(DecodeError) end context "when the implied expiration check is now" do it "raises an error if the token has expired" do tkn = subject.encode({'foo' => "bar", 'exp' => Time.now.to_i - 60 }) expect { subject.decode("bEaReR #{tkn}") }.to raise_exception(TokenExpired) end end context "when an explicit time stamp is provided for the expiration check" do it "raises an error if the token was expired at the specified time" do tkn = subject.encode({'foo' => "bar", 'exp' => Time.now.to_i - 30 }) expect { subject.decode_at_reference_time("bEaReR #{tkn}", Time.now.to_i - 20) }.to raise_exception(TokenExpired) end it "returns the decoded token if it was valid at the specified time" do tkn = subject.encode({'foo' => "bar", 'exp' => Time.now.to_i - 30 }) result = subject.decode_at_reference_time("bEaReR #{tkn}", Time.now.to_i - 100) result.should_not be_nil result["foo"].should == "bar" end end it "decodes a token without validation" do token = "<KEY>" info = TokenCoder.decode(token, :verify => false) info["id"].should_not be_nil info["email"].should == "<EMAIL>" end end end
pjk25/cf-uaa-lib
spec/info_spec.rb
#-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ require 'spec_helper' require 'uaa/info' module CF::UAA describe Info do let(:options) { {} } let(:uaa_info) { Info.new(target, options) } let(:target) { 'https://login.cloudfoundry.com' } let(:authorization) { nil } before do uaa_info.set_request_handler do |url, method, body, headers| url.should == target_url method.should == :get headers['content-type'].should be_nil headers['accept'].gsub(/\s/, '').should =~ /application\/json;charset=utf-8/i headers['authorization'].should == authorization [200, response_body, {'content-type' => 'application/json'}] end end describe 'initialize' do let(:options) { {:skip_ssl_validation => true} } it 'sets proxy information' do uaa_info.skip_ssl_validation == true end end describe 'getting server info' do let(:target_url) { 'https://login.cloudfoundry.com/login' } let(:response_body) { '{"commit_id":"12345","prompts":["one","two"]}' } it 'gets server info' do result = uaa_info.server result['prompts'].should_not be_nil result['commit_id'].should_not be_nil end context 'with symbolize_keys keys true' do let(:options) { {:symbolize_keys => true} } it 'gets server info' do result = uaa_info.server result[:prompts].should_not be_nil result[:commit_id].should_not be_nil end end end describe 'getting UAA target' do let(:target) { 'https://login.cloudfoundry.com' } let(:target_url) { 'https://login.cloudfoundry.com/login' } let(:response_body) { '{"links":{"uaa":"https://uaa.cloudfoundry.com"},"prompts":["one","two"]}' } it 'gets UAA target' do result = uaa_info.discover_uaa result.should == 'https://uaa.cloudfoundry.com' end context "when there is no 'links' key present" do let(:target) { 'https://uaa.cloudfoundry.com' } let(:target_url) { 'https://uaa.cloudfoundry.com/login' } let(:response_body) { '{ "prompts" : ["one","two"]} ' } it 'returns the target url' do result = uaa_info.discover_uaa result.should == 'https://uaa.cloudfoundry.com' end end context 'with symbolize_keys keys true' do let(:options) { {:symbolize_keys => true} } it 'gets UAA target' do result = uaa_info.discover_uaa result.should == 'https://uaa.cloudfoundry.com' end end end describe 'whoami' do let(:target_url) { 'https://login.cloudfoundry.com/userinfo?schema=openid' } let(:response_body) { '{"user_id":"1111-1111-1111-1111","user_name":"user","given_name":"first","family_name":"last","name":"first last","email":"<EMAIL>"}' } let(:authorization) { 'authentication_token' } it 'returns the user info' do result = uaa_info.whoami(authorization) result['email'].should == '<EMAIL>' end end describe 'validation_key' do let(:target_url) { 'https://login.cloudfoundry.com/token_key' } let(:response_body) { '{"alg":"SHA256withRSA","value":"-----BEGIN PUBLIC KEY-----\nabc123\n-----END PUBLIC KEY-----\n"}' } it 'returns the key data' do result = uaa_info.validation_key(authorization) result['alg'].should == 'SHA256withRSA' end end describe 'validation keys' do let(:target_url) { 'https://login.cloudfoundry.com/token_keys' } let(:response_body) { '{ "keys": [ { "kid": "the_key", "alg": "SHA256withRSA", "value": "-----BEGIN PUBLIC KEY-----\nabc123\n-----END PUBLIC KEY-----\n", "kty": "RSA", "use": "sig", "n": "Ufn7Qc", "e": "EEXZ" }, { "kid": "the_other_key", "alg": "SHA256withRSA", "value": "-----BEGIN PUBLIC KEY-----\ndef456\n-----END PUBLIC KEY-----\n", "kty": "RSA", "use": "sig", "n": "AMcW9/P", "e": "AQAB" } ] }' } it 'returns a hash of keys' do result = uaa_info.validation_keys_hash(authorization) the_key = result['the_key'] the_key.should_not be_nil the_other_key = result['the_other_key'] the_other_key.should_not be_nil the_key['alg'].should == 'SHA256withRSA' the_other_key['alg'].should == 'SHA256withRSA' the_key['value'].should == "-----BEGIN PUBLIC KEY-----\nabc123\n-----END PUBLIC KEY-----\n" the_other_key['value'].should == "-----BEGIN PUBLIC KEY-----\ndef456\n-----END PUBLIC KEY-----\n" end end end end
pjk25/cf-uaa-lib
cf-uaa-lib.gemspec
# -*- encoding: utf-8 -*- #-- # Cloud Foundry # Copyright (c) [2009-2014] Pivotal Software, Inc. All Rights Reserved. # # This product is licensed to you under the Apache License, Version 2.0 (the "License"). # You may not use this product except in compliance with the License. # # This product includes a number of subcomponents with # separate copyright notices and license terms. Your use of these # subcomponents is subject to the terms and conditions of the # subcomponent's license, as noted in the LICENSE file. #++ $:.push File.expand_path("../lib", __FILE__) require "uaa/version" Gem::Specification.new do |s| s.name = 'cf-uaa-lib' s.version = CF::UAA::VERSION s.authors = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>'] s.email = ['<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>'] s.homepage = 'https://github.com/cloudfoundry/cf-uaa-lib' s.summary = %q{Client library for CloudFoundry UAA} s.description = %q{Client library for interacting with the CloudFoundry User Account and Authorization (UAA) server. The UAA is an OAuth2 Authorization Server so it can be used by webapps and command line apps to obtain access tokens to act on behalf of users. The tokens can then be used to access protected resources in a Resource Server. This library is for use by UAA client applications or resource servers.} s.rubyforge_project = "cf-uaa-lib" s.license = "Apache-2.0" s.files = `git ls-files`.split("\n") s.test_files = `git ls-files -- {test,spec,features}/*`.split("\n") s.executables = `git ls-files -- bin/*`.split('\n').map{ |f| File.basename(f) } s.require_paths = ['lib'] # dependencies s.add_dependency 'multi_json', '~> 1.12.0', '>= 1.12.1' s.add_dependency 'httpclient', '~> 2.8', '>= 2.8.2.4' s.add_development_dependency 'bundler', '~> 1.14' s.add_development_dependency 'rake', '~> 10.3', '>= 10.3.2' s.add_development_dependency 'rspec', '~> 2.14', '>= 2.14.1' s.add_development_dependency 'simplecov', '~> 0.8.2' s.add_development_dependency 'simplecov-rcov', '~> 0.2.3' s.add_development_dependency 'ci_reporter', '~> 1.9', '>= 1.9.2' s.add_development_dependency 'json_pure', '~> 1.8', '>= 1.8.1' end