code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
def get_avail_fence_agents(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end agents = getFenceAgents(session) return JSON.generate(agents) end
Compound
4
def self.get_for(user_id, date) begin con = "(user_id=#{user_id}) and (date='#{date}')" return Timecard.where(con).first rescue end return nil end
Base
1
it "should fail when a protocol other than :puppet or :file is used" do @request.stubs(:protocol).returns "http" proc { @object.select_terminus(@request) }.should raise_error(ArgumentError) end
Class
2
def check_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? begin owner_id = Item.find(params[:id]).user_id rescue owner_id = -1 end if !@login_user.admin?(User::AUTH_ITEM) and owner_id != @login_user.id Log.add_check(request, '[check_owner]'+request.to_s) flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') end end
Base
1
def add_label options, f, attr label_size = options.delete(:label_size) || "col-md-2" required_mark = check_required(options, f, attr) label = options[:label] == :none ? '' : options.delete(:label) label ||= ((clazz = f.object.class).respond_to?(:gettext_translation_for_attribute_name) && s_(clazz.gettext_translation_for_attribute_name attr)) if f label = label.present? ? label_tag(attr, "#{label}#{required_mark}".html_safe, :class => label_size + " control-label") : '' label end
Base
1
def query Log.add_info(request, '') # Not to show passwords. unless @login_user.admin?(User::AUTH_ZEPTAIR) render(:text => 'ERROR:' + t('msg.need_to_be_admin')) return end target_user = nil SqlHelper.validate_token([params[:user_id], params[:zeptair_id], params[:group_id]]) unless params[:user_id].blank? target_user = User.find(params[:user_id]) end unless params[:zeptair_id].blank? zeptair_id = params[:zeptair_id] target_user = User.where("zeptair_id=#{zeptair_id}").first end if target_user.nil? if params[:group_id].blank? sql = 'select distinct Item.* from items Item, attachments Attachment' sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id" sql << ' order by Item.user_id ASC' else group_ids = [params[:group_id]] if params[:recursive] == 'true' group_ids += Group.get_childs(params[:group_id], true, false) end groups_con = [] group_ids.each do |group_id| groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{@group_id}|") end sql = 'select distinct Item.* from items Item, attachments Attachment, users User' sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id" sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))" sql << ' order by Item.user_id ASC' end @post_items = Item.find_by_sql(sql) else @post_item = ZeptairPostHelper.get_item_for(target_user) end rescue => evar Log.add_error(request, evar) render(:text => 'ERROR:' + t('msg.system_error')) end
Base
1
def send_request_with_token(session, node, request, post=false, data={}, remote=true, raw_data=nil, timeout=30, additional_tokens={}) token = additional_tokens[node] || get_node_token(node) $logger.info "SRWT Node: #{node} Request: #{request}" if not token $logger.error "Unable to connect to node #{node}, no token available" return 400,'{"notoken":true}' end cookies_data = { 'token' => token, } return send_request( session, node, request, post, data, remote, raw_data, timeout, cookies_data ) end
Compound
4
it "updates a hostgroup with a parent parameter" do child = FactoryGirl.create(:hostgroup, :parent => @base) as_admin do assert_equal "original", child.parameters["x"] end post :update, {"id" => child.id, "hostgroup" => {"name" => child.name, :group_parameters_attributes => {"0" => {:name => "x", :value =>"overridden", :_destroy => ""}}}}, set_session_user assert_redirected_to hostgroups_url child.reload assert_equal "overridden", child.parameters["x"] end
Class
2
def search Log.add_info(request, params.inspect) unless params[:select_sorting].nil? or params[:select_sorting].empty? sort_a = params[:select_sorting].split(' ') params[:sort_col] = sort_a.first params[:sort_type] = sort_a.last end list if params[:keyword].nil? or params[:keyword].empty? if params[:from_action].nil? or params[:from_action] == 'bbs' render(:action => 'bbs') else render(:action => 'list') end end end
Base
1
it "creates an index with a generated name" do indexes.create(key) indexes[key]["name"].should eq "location.latlong_2d_name_1_age_-1" end
Class
2
def initialize # Generate and cache 3 bytes of identifying information from the current # machine. @machine_id = Digest::MD5.digest(Socket.gethostname).unpack("C3") @mutex = Mutex.new @last_timestamp = nil @counter = 0 end
Class
2
def test_update_valid AuthSourceLdap.any_instance.stubs(:valid?).returns(true) put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user assert_redirected_to auth_source_ldaps_url end
Class
2
def with_taxonomy_scope(loc = Location.current, org = Organization.current, inner_method = :subtree_ids) self.which_ancestry_method = inner_method self.which_location = Location.expand(loc) if SETTINGS[:locations_enabled] self.which_organization = Organization.expand(org) if SETTINGS[:organizations_enabled] scope = block_given? ? yield : where('1=1') scope = scope_by_taxable_ids(scope) scope.readonly(false) end
Class
2
def get_corosync_nodes() stdout, stderror, retval = run_cmd( PCSAuth.getSuperuserSession, PCS, "status", "nodes", "corosync" ) if retval != 0 return [] end stdout.each {|x| x.strip!} corosync_online = stdout[1].sub(/^.*Online:/,"").strip corosync_offline = stdout[2].sub(/^.*Offline:/,"").strip corosync_nodes = (corosync_online.split(/ /)) + (corosync_offline.split(/ /)) return corosync_nodes end
Compound
4
def setup_user @request.session[:user] = users(:one).id users(:one).roles = [Role.default, Role.find_by_name('Viewer')] end
Class
2
def remote_address @request.forwarded_for || socket_address rescue Exception log_error nil end
Class
2
def self.get_for(user_id, fiscal_year=nil) SqlHelper.validate_token([user_id, fiscal_year]) begin con = [] con << "(user_id=#{user_id})" if fiscal_year.nil? return PaidHoliday.where(con).order('year ASC').to_a else con << "(year=#{fiscal_year})" return PaidHoliday.where(con.join(' and ')).first end rescue end return nil end
Base
1
def perform_accept_invitation params.require(:id) params.permit(:email, :username, :name, :password, :timezone, :email_token, user_custom_fields: {}) invite = Invite.find_by(invite_key: params[:id]) if invite.present? begin attrs = { username: params[:username], name: params[:name], password: params[:password], user_custom_fields: params[:user_custom_fields], ip_address: request.remote_ip, session: session } if invite.is_invite_link? params.require(:email) attrs[:email] = params[:email] else attrs[:email] = invite.email attrs[:email_token] = params[:email_token] if params[:email_token].present? end user = invite.redeem(**attrs) rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved, Invite::UserExists => e return render json: failed_json.merge(message: e.message), status: 412 end if user.blank? return render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404 end log_on_user(user) if user.active? user.update_timezone_if_missing(params[:timezone]) post_process_invite(user) create_topic_invite_notifications(invite, user) topic = invite.topics.first response = {} if user.present? if user.active? if user.guardian.can_see?(topic) response[:redirect_to] = path(topic.relative_url) else response[:redirect_to] = path("/") end else response[:message] = I18n.t('invite.confirm_email') if user.guardian.can_see?(topic) cookies[:destination_url] = path(topic.relative_url) end end end render json: success_json.merge(response) else render json: failed_json.merge(message: I18n.t('invite.not_found_json')), status: 404 end end
Class
2
it 'should verify a standard RS256 token' do domain = 'example.org' sub = 'abc123' payload = { sub: sub, exp: future_timecode, iss: "https://#{domain}/", iat: past_timecode, aud: client_id, kid: jwks_kid } token = make_rs256_token(payload) verified_token = make_jwt_validator(opt_domain: domain).verify(token) expect(verified_token['sub']).to eq(sub) end
Base
1
def execute(op) mode = options[:consistency] == :eventual ? :read : :write socket = socket_for(mode) if safe? last_error = Protocol::Command.new( "admin", { getlasterror: 1 }.merge(safety) ) socket.execute(op, last_error).documents.first.tap do |result| raise Errors::OperationFailure.new( op, result ) if result["err"] || result["errmsg"] end else socket.execute(op) end end
Class
2
it "approves user if invited by staff" do SiteSetting.must_approve_users = true invite = Fabricate(:invite, email: '[email protected]', invited_by: Fabricate(:admin)) user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'test') expect(user.approved).to eq(true) end
Class
2
it "handles Symbol keys with underscore and tailing '='" do cl = subject.build_command_line("true", :abc_def= => "ghi") expect(cl).to eq "true --abc-def=ghi" end
Base
1
it "should redeem the invite if invited by non staff but not approve" do SiteSetting.must_approve_users = true inviter = invite.invited_by user = invite_redeemer.redeem expect(user.name).to eq(name) expect(user.username).to eq(username) expect(user.invited_by).to eq(inviter) expect(inviter.notifications.count).to eq(1) expect(user.approved).to eq(false) end
Class
2
def as_json(options = {}) hash = super hash["secret"] = plaintext_secret if hash.key?("secret") hash end
Class
2
def initialize(session, configs, nodes, cluster_name, tokens={}) @configs = configs @nodes = nodes @cluster_name = cluster_name @published_configs_names = @configs.collect { |cfg| cfg.class.name } @additional_tokens = tokens @session = session end
Compound
4
it "yields a new session" do session.with(new_options) do |new_session| new_session.should_not eql session end end
Class
2
def add_group(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end rg = params["resource_group"] resources = params["resources"] output, errout, retval = run_cmd( session, PCS, "resource", "group", "add", rg, *(resources.split(" ")) ) if retval == 0 return 200 else return 400, errout end end
Compound
4
def sync_server(server) [].tap do |hosts| socket = server.socket if socket.connect info = socket.simple_query Protocol::Command.new(:admin, ismaster: 1) if info["ismaster"] server.primary = true end if info["secondary"] server.secondary = true end if info["primary"] hosts.push info["primary"] end if info["hosts"] hosts.concat info["hosts"] end if info["passives"] hosts.concat info["passives"] end merge(server) end end.uniq end
Class
2
def taxable_ids(loc = which_location, org = which_organization, inner_method = which_ancestry_method) if SETTINGS[:locations_enabled] && loc.present? inner_ids_loc = if Location.ignore?(self.to_s) self.unscoped.pluck("#{table_name}.id") else inner_select(loc, inner_method) end end
Class
2
def run_cmd(session, *args) options = {} return run_cmd_options(session, options, *args) end
Compound
4
def check_mail_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? begin owner_id = Email.find(params[:id]).user_id rescue owner_id = -1 end if !@login_user.admin?(User::AUTH_MAIL) and owner_id != @login_user.id Log.add_check(request, '[check_mail_owner]'+request.to_s) flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') end end
Base
1
def call(env) return @app.call(env) unless env['PATH_INFO'].start_with? "#{@bus.base_route}message-bus/_diagnostics" route = env['PATH_INFO'].split("#{@bus.base_route}message-bus/_diagnostics")[1] if @bus.is_admin_lookup.nil? || [email protected]_admin_lookup.call(env) return [403, {}, ['not allowed']] end return index unless route if route == '/discover' user_id = @bus.user_id_lookup.call(env) @bus.publish('/_diagnostics/discover', user_id: user_id) return [200, {}, ['ok']] end if route =~ /^\/hup\// hostname, pid = route.split('/hup/')[1].split('/') @bus.publish('/_diagnostics/hup', hostname: hostname, pid: pid.to_i) return [200, {}, ['ok']] end asset = route.split('/assets/')[1] if asset && !asset !~ /\// content = asset_contents(asset) return [200, { 'Content-Type' => 'application/javascript;charset=UTF-8' }, [content]] end [404, {}, ['not found']] end
Base
1
it "updates the record matching selector with change" do session.should_receive(:with, :consistency => :strong). and_yield(session) session.should_receive(:execute).with do |update| update.flags.should eq [] update.selector.should eq query.operation.selector update.update.should eq change end query.update change end
Class
2
it "raises an OperationFailure exception" do session.stub(socket_for: socket) socket.stub(execute: reply) expect { session.execute(operation) }.to raise_exception(Moped::Errors::OperationFailure) end
Class
2
it "memoizes the database" do database = session.current_database session.current_database.should equal(database) end
Class
2
def remote_pcsd_restart(params, request, session) pcsd_restart() return [200, 'success'] end
Compound
4
it "yields the new session" do session.stub(with: new_session) session.new(new_options) do |session| session.should eql new_session end end
Class
2
def has_cookie? [email protected]? end
Class
2
it "sanitizes Fixnum array param value" do cl = subject.build_command_line("true", nil => [1]) expect(cl).to eq "true 1" end
Base
1
it "drops the index that matches the key" do indexes[name: 1].should be_nil end
Class
2
def decode_compact_serialized(input, private_key_or_secret, algorithms = nil, encryption_methods = nil, _allow_blank_payload = false) unless input.count('.') + 1 == NUM_OF_SEGMENTS raise InvalidFormat.new("Invalid JWE Format. JWE should include #{NUM_OF_SEGMENTS} segments.") end jwe = new _header_json_, jwe.jwe_encrypted_key, jwe.iv, jwe.cipher_text, jwe.authentication_tag = input.split('.').collect do |segment| begin Base64.urlsafe_decode64 segment rescue ArgumentError raise DecryptionFailed end end jwe.auth_data = input.split('.').first jwe.header = JSON.parse(_header_json_).with_indifferent_access unless private_key_or_secret == :skip_decryption jwe.decrypt! private_key_or_secret, algorithms, encryption_methods end jwe end
Class
2
def resource_status(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end resource_id = params[:resource] @resources,@groups = getResourcesGroups(session) location = "" res_status = "" @resources.each {|r| if r.id == resource_id if r.failed res_status = "Failed" elsif !r.active res_status = "Inactive" else res_status = "Running" end if r.nodes.length != 0 location = r.nodes[0].name break end end } status = {"location" => location, "status" => res_status} return JSON.generate(status) end
Compound
4
def self.loginByPassword(session, username, password) if validUser(username, password) session[:username] = username success, groups = getUsersGroups(username) session[:usergroups] = success ? groups : [] return true end return false end
Compound
4
def get_resource_agents_avail(session) code, result = send_cluster_request_with_token( session, params[:cluster], 'get_avail_resource_agents' ) return {} if 200 != code begin ra = JSON.parse(result) if (ra["noresponse"] == true) or (ra["notauthorized"] == "true") or (ra["notoken"] == true) or (ra["pacemaker_not_running"] == true) return {} else return ra end rescue JSON::ParserError return {} end end
Compound
4
it "sets the query operation's skip field" do query.skip(5) query.operation.skip.should eq 5 end
Class
2
def filter_archived(list, user, archived: true) # Executing an extra query instead of a sub-query because it is more # efficient for the PG planner. Caution should be used when changing the # query here as it can easily lead to an inefficient query. group_ids = group_with_messages_ids(user) list = list.joins(<<~SQL) LEFT JOIN group_archived_messages gm ON gm.topic_id = topics.id #{group_ids.present? ? "AND gm.group_id IN (#{group_ids.join(",")})" : ""} LEFT JOIN user_archived_messages um ON um.user_id = #{user.id.to_i} AND um.topic_id = topics.id SQL list = if archived list.where("um.user_id IS NOT NULL OR gm.topic_id IS NOT NULL") else list.where("um.user_id IS NULL AND gm.topic_id IS NULL") end list end
Class
2
it "returns the new session" do session.stub(with: new_session) session.new(new_options).should eql new_session end
Class
2
def update_fence_device(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end $logger.info "Updating fence device" $logger.info params param_line = getParamList(params) $logger.info param_line if not params[:resource_id] out, stderr, retval = run_cmd( session, PCS, "stonith", "create", params[:name], params[:resource_type], *param_line ) if retval != 0 return JSON.generate({"error" => "true", "stderr" => stderr, "stdout" => out}) end return "{}" end if param_line.length != 0 out, stderr, retval = run_cmd( session, PCS, "stonith", "update", params[:resource_id], *param_line ) if retval != 0 return JSON.generate({"error" => "true", "stderr" => stderr, "stdout" => out}) end end return "{}" end
Compound
4
def api_endpoint(uri) host = uri.host begin res = @dns.getresource "_rubygems._tcp.#{host}", Resolv::DNS::Resource::IN::SRV rescue Resolv::ResolvError => e verbose "Getting SRV record failed: #{e}" uri else target = res.target.to_s.strip if /\.#{Regexp.quote(host)}\z/ =~ target return URI.parse "#{uri.scheme}://#{target}#{uri.path}" end uri end end
Class
2
it "executes the operation on the master node" do session.should_receive(:socket_for).with(:write). and_return(socket) socket.should_receive(:execute).with(operation) session.execute(operation) end
Class
2
it "syncs the cluster" do cluster.should_receive(:sync) do cluster.servers << server end cluster.socket_for :write end
Class
2
def initialize(locale, key, options = nil) @key, @locale, @options = key, locale, options.dup || {} options.each { |k, v| self.options[k] = v.inspect if v.is_a?(Proc) } end def html_message key = keys.last.to_s.gsub('_', ' ').gsub(/\b('?[a-z])/) { $1.capitalize } %(<span class="translation_missing" title="translation missing: #{keys.join('.')}">#{key}</span>) end def keys @keys ||= I18n.normalize_keys(locale, key, options[:scope]).tap do |keys| keys << 'no key' if keys.size < 2 end end def message "translation missing: #{keys.join('.')}" end
Base
1
def add_constraint_set_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end case params["c_type"] when "ord" retval, error = add_order_set_constraint( session, params["resources"].values, params["force"], !params['disable_autocorrect'] ) else return [400, "Unknown constraint type: #{params["c_type"]}"] end
Compound
4
def check_owner return if params[:id].nil? or params[:id].empty? or @login_user.nil? mail_account = MailAccount.find(params[:id]) if !@login_user.admin?(User::AUTH_MAIL) and mail_account.user_id != @login_user.id Log.add_check(request, '[check_owner]'+request.to_s) flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') end end
Base
1
def get_mail_content Log.add_info(request, params.inspect) mail_id = params[:id] begin @email = Email.find(mail_id) render(:partial => 'ajax_mail_content', :layout => false) rescue => evar Log.add_error(nil, evar) render(:text => '') end end
Base
1
def dup session = super session.instance_variable_set :@options, options.dup if defined? @current_database session.send(:remove_instance_variable, :@current_database) end session end
Class
2
def read_body(socket, block) return unless socket if tc = self['transfer-encoding'] case tc when /chunked/io then read_chunked(socket, block) else raise HTTPStatus::NotImplemented, "Transfer-Encoding: #{tc}." end elsif self['content-length'] || @remaining_size @remaining_size ||= self['content-length'].to_i while @remaining_size > 0 sz = [@buffer_size, @remaining_size].min break unless buf = read_data(socket, sz) @remaining_size -= buf.bytesize block.call(buf) end if @remaining_size > 0 && @socket.eof? raise HTTPStatus::BadRequest, "invalid body size." end elsif BODY_CONTAINABLE_METHODS.member?(@request_method) && [email protected] raise HTTPStatus::LengthRequired end
Base
1
def self.get_for(user_id, date_s) SqlHelper.validate_token([user_id, date_s]) begin con = "(user_id=#{user_id}) and (date='#{date_s}')" return Timecard.where(con).first rescue end return nil end
Base
1
it "should be an error instance if file was downloaded" do stub_request(:get, "www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg"))) @instance.remote_image_url = "http://www.example.com/test.jpg" e = @instance.image_integrity_error expect(e).to be_an_instance_of(CarrierWave::IntegrityError) expect(e.message.lines.grep(/^You are not allowed to upload/)).to be_truthy end
Base
1
it "delegates to the current database" do database = mock(Moped::Database) session.should_receive(:current_database).and_return(database) database.should_receive(:drop) session.drop end
Class
2
def _unmarshal(val, options) unmarshal?(val, options) ? Marshal.load(val) : val end
Base
1
def comment_link(uniqueid, data) comment = comment_for_type(data) i18n_key = data[:cutoff] ? 'truncated' : 'full' notification = t( "notifications.comment.#{i18n_key}", name: data[:user], comment: strip_tags(data[:comment]), typename: data[:typename] ) notification_link(uniqueid, comment[:path], notification) end
Base
1
it 'returns success' do get "/session/email-login/#{email_token.token}" expect(response).to redirect_to("/") end
Class
2
def get_node_attributes(session, cib_dom=nil) unless cib_dom cib_dom = get_cib_dom(session) return {} unless cib_dom end node_attrs = {} cib_dom.elements.each( '/cib/configuration/nodes/node/instance_attributes/nvpair' ) { |e| node = e.parent.parent.attributes['uname'] node_attrs[node] ||= [] node_attrs[node] << { :id => e.attributes['id'], :key => e.attributes['name'], :value => e.attributes['value'] } } node_attrs.each { |_, val| val.sort_by! { |obj| obj[:key] }} return node_attrs end
Compound
4
it "approves pending record" do reviewable = ReviewableUser.needs_review!(target: Fabricate(:user, email: invite.email), created_by: invite.invited_by) reviewable.status = Reviewable.statuses[:pending] reviewable.save! invite_redeemer.redeem reviewable.reload expect(reviewable.status).to eq(Reviewable.statuses[:approved]) end
Class
2
def output_versions output, versions versions.each do |gem_name, matching_tuples| matching_tuples = matching_tuples.sort_by { |n,_| n.version }.reverse platforms = Hash.new { |h,version| h[version] = [] } matching_tuples.each do |n, _| platforms[n.version] << n.platform if n.platform end seen = {} matching_tuples.delete_if do |n,_| if seen[n.version] then true else seen[n.version] = true false end end output << make_entry(matching_tuples, platforms) end end
Base
1
it "initializes with the strings bytes" do Moped::BSON::ObjectId.should_receive(:new).with(bytes) Moped::BSON::ObjectId.from_string "4e4d66343b39b68407000001" end
Class
2
def paginate_by_sql(model, sql, per_page, options={}) if options[:count] if options[:count].is_a?(Integer) total = options[:count] else total = model.count_by_sql(options[:count]) end else total = model.count_by_sql_wrapping_select_query(sql) end object_pages = model.paginate_by_sql(sql, {:page => params['page'], :per_page => per_page}) #objects = model.find_by_sql_with_limit(sql, object_pages.current.to_sql[1], per_page) return [object_pages, object_pages, total] end
Base
1
detectExtension(mimeType) { if (!mimeType) { return defaultExtension; } let parts = (mimeType || '') .toLowerCase() .trim() .split('/'); let rootType = parts.shift().trim(); let subType = parts.join('/').trim(); if (mimeTypes.has(rootType + '/' + subType)) { let value = mimeTypes.get(rootType + '/' + subType); if (Array.isArray(value)) { return value[0]; } return value; } switch (rootType) { case 'text': return 'txt'; default: return 'bin'; } }
Base
1
def self.validate_token(tokens, extra_chars=nil) if extra_chars.nil? extra_chars = '' else extra_chars = Regexp.escape(extra_chars.join()) end regexp = Regexp.new("^[ ]*[a-zA-Z0-9_.@\\-#{extra_chars}]+[ ]*$") [tokens].flatten.each do |token| next if token.blank? if token.to_s.match(regexp).nil? raise("[ERROR] SqlHelper.validate_token failed: #{token}") end end end
Base
1
def discard_cookie!(headers) Rack::Utils.delete_cookie_header!(headers, COOKIE_NAME, :path => '/') end
Class
2
it "includes plaintext secret" do expect(app.as_json).to include("secret" => "123123123") end
Class
2
it "drops all indexes for the collection" do indexes[name: 1].should be_nil indexes[age: -1].should be_nil end
Class
2
def legal?(string) string.to_s =~ /^[0-9a-f]{24}$/i ? true : false end
Class
2
def test_update_valid Medium.any_instance.stubs(:valid?).returns(true) put :update, {:id => Medium.first, :medium => {:name => "MyUpdatedMedia"}}, set_session_user assert_redirected_to media_url end
Class
2
it "stores the cluster" do session.cluster.should be_a(Moped::Cluster) end
Class
2
def get_auth_groups Log.add_info(request, params.inspect) begin @folder = Folder.find(params[:id]) rescue @folder = nil end @groups = Group.where(nil).to_a session[:folder_id] = params[:id] render(:partial => 'ajax_auth_groups', :layout => false) end
Base
1
def on_moved Log.add_info(request, params.inspect) location_id = params[:id] if location_id.nil? or location_id.empty? location = Location.get_for(@login_user) if location.nil? location = Location.new location.user_id = @login_user.id end else begin location = Location.find(location_id) rescue end end unless location.nil? group_id = params[:group_id] group_id = nil if group_id.empty? attrs = ActionController::Parameters.new({group_id: group_id, x: params[:x], y: params[:y]}) location.update_attributes(attrs.permit(Location::PERMIT_BASE)) end render(:text => (location.nil?)?'':location.id.to_s) end
Base
1
def send_cluster_request_with_token(session, cluster_name, request, post=false, data={}, remote=true, raw_data=nil) $logger.info("SCRWT: " + request) nodes = get_cluster_nodes(cluster_name) return send_nodes_request_with_token( session, nodes, request, post, data, remote, raw_data ) end
Compound
4
it "should choose :rest when the Settings name isn't 'puppet'" do @request.stubs(:protocol).returns "puppet" @request.stubs(:server).returns "foo" Puppet.settings.stubs(:value).with(:name).returns "foo" @object.select_terminus(@request).should == :rest end
Class
2
def kill session.execute kill_cursor_op end
Class
2
it "applies the cached authentication" do cluster.stub(:sync) { cluster.servers << server } socket.should_receive(:apply_auth).with(cluster.auth) cluster.socket_for(:write) end
Class
2
def legal?(str) !!str.match(/^[0-9a-f]{24}$/i) end
Class
2
it "raises an exception" do expect { session.current_database }.to raise_exception end
Class
2
it "doesn't log in the user when not approved" do SiteSetting.must_approve_users = true get "/session/email-login/#{email_token.token}" expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to include( I18n.t("login.not_approved") ) end
Class
2
def getFenceAgents(session, fence_agent = nil) fence_agent_list = {} agents = Dir.glob('/usr/sbin/fence_' + '*') agents.each { |a| fa = FenceAgent.new fa.name = a.sub(/.*\//,"") next if fa.name == "fence_ack_manual" if fence_agent and a.sub(/.*\//,"") == fence_agent.sub(/.*:/,"") required_options, optional_options, advanced_options, info = getFenceAgentMetadata(session, fa.name) fa.required_options = required_options fa.optional_options = optional_options fa.advanced_options = advanced_options fa.info = info end fence_agent_list[fa.name] = fa } fence_agent_list end
Compound
4
it "sets slave_ok on the query flags" do session.stub(socket_for: socket) socket.should_receive(:execute) do |query| query.flags.should include :slave_ok end session.query(query) end
Class
2
def get_order Log.add_info(request, params.inspect) mail_account_id = params[:mail_account_id] @mail_account = MailAccount.find_by_id(mail_account_id) if @mail_account.user_id != @login_user.id flash[:notice] = t('msg.need_to_be_owner') redirect_to(:controller => 'desktop', :action => 'show') return end @mail_filters = MailFilter.get_for(mail_account_id) render(:partial => 'ajax_order', :layout => false) rescue => evar Log.add_error(request, evar) render(:partial => 'ajax_order', :layout => false) end
Base
1
it "should find a user by first name and last name" do @cur_user.stub(:pref).and_return(:activity_user => 'Billy Elliot') controller.instance_variable_set(:@current_user, @cur_user) User.should_receive(:where).with("(upper(first_name) LIKE upper('%Billy%') AND upper(last_name) LIKE upper('%Elliot%')) OR (upper(first_name) LIKE upper('%Elliot%') AND upper(last_name) LIKE upper('%Billy%'))").and_return([@user]) controller.send(:activity_user).should == 1 end
Base
1
def setup @store = Redis::Store.new :marshalling => true @rabbit = OpenStruct.new :name => "bunny" @white_rabbit = OpenStruct.new :color => "white" @store.set "rabbit", @rabbit @store.del "rabbit2" end
Base
1
it "sanitizes Pathname param key" do cl = subject.build_command_line("true", Pathname.new("/usr/bin/ruby") => nil) expect(cl).to eq "true /usr/bin/ruby" end
Base
1
def show Log.add_info(request, params.inspect) @group_id = params[:group_id] official_title_id = params[:id] unless official_title_id.nil? or official_title_id.empty? @official_title = OfficialTitle.find(official_title_id) end render(:layout => (!request.xhr?)) end
Base
1
def test_login_should_not_redirect_to_another_host post :login, :username => 'jsmith', :password => 'jsmith', :back_url => 'http://test.foo/fake' assert_redirected_to '/my/page' end
Class
2
def index valid_http_methods :get, :post, :put # for permission check if params[:package] and not ["_repository", "_jobhistory"].include?(params[:package]) pkg = DbPackage.get_by_project_and_name( params[:project], params[:package], use_source=false ) else prj = DbProject.get_by_name params[:project] end pass_to_backend end
Base
1
def initialize(session, query_operation) @session = session @query_op = query_operation.dup @get_more_op = Protocol::GetMore.new( @query_op.database, @query_op.collection, 0, @query_op.limit ) @kill_cursor_op = Protocol::KillCursors.new([0]) end
Class
2
def self.get_comment_of(item_id, user_id) SqlHelper.validate_token([item_id, user_id]) begin comment = Comment.where("(user_id=#{user_id}) and (item_id=#{item_id}) and (xtype='#{Comment::XTYPE_DIST_ACK}')").first rescue => evar Log.add_error(nil, evar) end return comment end
Base
1
def updated_ajax @user = current_site.users.find(params[:user_id]) render inline: @user.update(params.require(:password).permit!) ? "" : @user.errors.full_messages.join(', ') end
Base
1
def set_inboxes @inbox_ids = if params[:inbox_id] current_account.inboxes.where(id: params[:inbox_id]) else @current_user.assigned_inboxes.pluck(:id) end
Class
2
def destroy current_user.invalidate_all_sessions! super end
Base
1
it "stores the cluster" do session.cluster.should be_a(Moped::Cluster) end
Class
2