code
stringlengths
12
2.05k
label_name
stringclasses
5 values
label
int64
0
4
it 'is possible to return hash errors in jsonapi format' do get '/' expect(['{"error":"rain!","detail":"missing widget"}', '{"detail":"missing widget","error":"rain!"}']).to include(last_response.body) end
Base
1
def test_should_sanitize_with_trailing_space raw = "display:block; " expected = "display: block;" assert_equal expected, sanitize_css(raw) end
Base
1
it "raises an error when trying to download a local file" do expect { subject.download('/etc/passwd') }.to raise_error(CarrierWave::DownloadError) end
Base
1
def add_location_constraint_rule( session, resource, rule, score, force=false, autocorrect=true ) cmd = [PCS, "constraint", "location", resource, "rule"] if score != '' if is_score(score.upcase) cmd << "score=#{score.upcase}" else cmd << "score-attribute=#{score}" end end cmd.concat(ru...
Compound
4
it 'should return the right response' do email_token.update!(created_at: 999.years.ago) get "/session/email-login/#{email_token.token}" expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to match( I18n.t('email_login.invalid_token') ...
Class
2
def socket_for(mode) if options[:retain_socket] @socket ||= cluster.socket_for(mode) else cluster.socket_for(mode) end end
Class
2
def verify_cert_key_pair(cert, key) errors = [] cert_modulus = nil key_modulus = nil stdout, stderr, retval = run_cmd_options( PCSAuth.getSuperuserSession(), { 'stdin' => cert, }, '/usr/bin/openssl', 'x509', '-modulus', '-noout' ) if retval != 0 errors << "Invalid certificate: #{s...
Compound
4
it "does not change the original session's options" do original_options = options.dup session.with(new_options) do |new_session| session.options.should eql original_options end end
Class
2
it 'returns a list of all private messages that has been archived' do UserArchivedMessage.archive!(user_2.id, private_message) GroupArchivedMessage.archive!(user_2.id, group_message) topics = TopicQuery.new(nil).list_private_messages_all_archive(user_2).topics expect(topics).to contain_exa...
Class
2
def resource_metadata(params, request, session) if not allowed_for_local_cluster(session, Permissions::READ) return 403, 'Permission denied' end return 200 if not params[:resourcename] or params[:resourcename] == "" resource_name = params[:resourcename][params[:resourcename].rindex(':')+1..-1] class_provi...
Compound
4
def call(exception, locale, key, options) if exception.is_a?(MissingTranslation) options[:rescue_format] == :html ? exception.html_message : exception.message elsif exception.is_a?(Exception) raise exception else throw :exception, exception end e...
Base
1
it "should unstage user" do staged_user = Fabricate(:staged, email: 'staged@account.com', active: true, username: 'staged1', name: 'Stage Name') invite = Fabricate(:invite, email: 'staged@account.com') user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'wa...
Class
2
def first session.simple_query(operation) end
Class
2
it 'fails when local logins via email is disabled' do SiteSetting.enable_local_logins_via_email = false get "/session/email-login/#{email_token.token}" expect(response.status).to eq(404) end
Class
2
def get_cluster_name() if ISRHEL6 stdout, stderror, retval = run_cmd( PCSAuth.getSuperuserSession, COROSYNC_CMAPCTL, "cluster" ) if retval == 0 stdout.each { |line| match = /^cluster\.name=(.*)$/.match(line) return match[1] if match } end begin cluster_conf ...
Compound
4
def send_local_configs_to_nodes( session, nodes, force=false, clear_local_permissions=false ) configs = Cfgsync::get_configs_local(true) if clear_local_permissions pcs_config = PCSConfig.new(configs[Cfgsync::PcsdSettings.name].text()) pcs_config.permissions_local = Permissions::PermissionsSet.new([]) ...
Compound
4
def test_verify_security_policy_checksum_missing skip 'openssl is missing' unless defined?(OpenSSL::SSL) @spec.cert_chain = [PUBLIC_CERT.to_pem] @spec.signing_key = PRIVATE_KEY build = Gem::Package.new @gem build.spec = @spec build.setup_signer FileUtils.mkdir 'lib' FileUtils.touch ...
Base
1
def self.set_statistics_groups(group_ids) yaml = Research.get_config_yaml yaml = Hash.new if yaml.nil? if group_ids.nil? unless yaml[:statistics].nil? yaml[:statistics].delete :groups end else if yaml[:statistics].nil? yaml[:statistics] = Hash.new end ...
Base
1
def index respond_to do |format| format.json do dir = params[:dir] dir = 'desc' unless SORT_DIRECTIONS.include?(dir.try(:upcase)) @occurrences = @bug.occurrences.order("occurred_at #{dir}").limit(50) last = params[:last].present? ? @bug.occurrences.find_by_number(params[:la...
Base
1
def login Log.add_info(request, '') # Not to show passwords. user = User.authenticate(params[:user]) if user.nil? flash[:notice] = '<span class=\'font_msg_bold\'>'+t('user.u_name')+'</span>'+t('msg.or')+'<span class=\'font_msg_bold\'>'+t('password.name')+'</span>'+t('msg.is_invalid') if ...
Base
1
it "re-enabled functionality if whitelisted" do Rack::MiniProfiler.config.authorization_mode = :whitelist expect(Rack::MiniProfiler).to receive(:request_authorized?) { true }.twice get '/html?pp=enable' last_response.body.should include('/mini-profiler-resources/includes.js') ...
Class
2
it "returns the group permissions for everyone group too" do category.set_permissions(everyone: :readonly) category.save! json = described_class.new(category, scope: Guardian.new(admin), root: false).as_json expect(json[:group_permissions]).to eq([ { permission_type: Ca...
Base
1
it 'fails when local logins via email is disabled' do SiteSetting.enable_local_logins_via_email = false get "/session/email-login/#{email_token.token}" expect(response.status).to eq(404) end
Class
2
def cluster_destroy(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end out, errout, retval = run_cmd(session, PCS, "cluster", "destroy") if retval == 0 return [200, "Successfully destroyed cluster"] else return [400, "Error de...
Compound
4
def current_user User.except_hidden.find_by_login(self.user) end
Class
2
def new Log.add_info(request, params.inspect) mail_account_id = params[:mail_account_id] if mail_account_id.nil? or mail_account_id.empty? account_xtype = params[:mail_account_xtype] @mail_account = MailAccount.get_default_for(@login_user.id, account_xtype) else @mail_account = Mai...
Base
1
def testLoginByToken users = [] users << {"username" => "user1", "token" => "token1"} users << {"username" => "user2", "token" => "token2"} users << {"username" => SUPERUSER, "token" => "tokenS"} password_file = File.open($user_pass_file, File::RDWR|File::CREAT) password_file.truncate(0) p...
Compound
4
def self.get_for(user_id) SqlHelper.validate_token([user_id]) return Research.where("user_id=#{user_id}").first end
Base
1
it 'should not choke on valueless attributes' do @s.fragment('foo <a href>foo</a> bar') .must_equal 'foo <a href="" rel="nofollow">foo</a> bar' end
Class
2
def cluster_disable(params, request, session) if params[:name] code, response = send_request_with_token( session, params[:name], 'cluster_disable', true ) else if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end success = disable_cluster(...
Compound
4
it "has an empty list of primaries" do cluster.primaries.should be_empty end
Class
2
def remote_add_node(params, request, session, all=false) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end auto_start = false if params[:auto_start] and params[:auto_start] == "1" auto_start = true end if params[:new_nodename] != nil node = params[...
Compound
4
def initialize(name, value = nil, charset = 'utf-8') case when name =~ /:/ # Field.new("field-name: field data") @charset = value.blank? ? charset : value @name, @value = split(name) when name !~ /:/ && value.blank? # Field.new("field-name") @name = name ...
Base
1
def process_preflight(env) result = Result.preflight(env) resource, error = match_resource(env) unless resource result.miss(error) return {} end return resource.process_preflight(env, result) end
Base
1
def user_with_viewer_rights_should_fail_to_edit_a_domain setup_users get :edit, {:id => Domain.first.id} assert @response.status == '403 Forbidden' end
Class
2
def create_workflow Log.add_info(request, params.inspect) @tmpl_folder, @tmpl_workflows_folder = TemplatesHelper.get_tmpl_subfolder(TemplatesHelper::TMPL_WORKFLOWS) @group_id = params[:group_id] if @group_id.nil? or @group_id.empty? @group_id = '0' # '0' for ROOT elsif @group_id == '0' ...
Base
1
it "yields all documents in the cursor" do cursor = Moped::Cursor.allocate cursor.stub(:to_enum).and_return([1, 2].to_enum) Moped::Cursor.stub(new: cursor) query.to_a.should eq [1, 2] end
Class
2
def piped_category_name(category_id) return "-" unless category_id category = Category.find_by(id: category_id) return "#{category_id}" unless category categories = [category.name] while category.parent_category_id && category = category.parent_category categories << category.n...
Class
2
def properly_encode(fragment, options) fragment.xml? ? fragment.to_xml(options) : fragment.to_html(options) end
Base
1
it 'sets file extension based on content-type if missing' do expect(subject.original_filename).to eq "test.jpeg" end
Base
1
it "adds the server to the list" do cluster.sync_server server cluster.servers.should include server end
Class
2
it "returns an enumerator" do cursor = mock(Moped::Cursor) Moped::Cursor.stub(new: cursor) query.each.should be_a Enumerator end
Class
2
def resource_cleanup(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end stdout, stderr, retval = run_cmd( session, PCS, "resource", "cleanup", params[:resource] ) if retval == 0 return JSON.generate({"success" => "true"}) e...
Compound
4
def private_messages_for(user, type) options = @options options.reverse_merge!(per_page: per_page_setting) result = Topic.includes(:allowed_users) result = result.includes(:tags) if SiteSetting.tagging_enabled if type == :group result = result.joins( "INNER JOIN top...
Class
2
def create_event(comment) Event.create! bug_id: comment.bug_id, kind: 'comment', data: {'comment_id' => comment.id}, user_id: comment.user_id end
Base
1
def setup @namespace = "theplaylist" @store = Redis::Store.new :namespace => @namespace, :marshalling => false # TODO remove mashalling option @client = @store.instance_variable_get(:@client) @rabbit = "bunny" @default_store = Redis::Store.new @other_namespace = 'other' @other_store = Red...
Base
1
def stub_jwks stub_request(:get, 'https://samples.auth0.com/.well-known/jwks.json') .to_return( headers: { 'Content-Type' => 'application/json' }, body: jwks.to_json, status: 200 ) end
Base
1
def check_auth(params, request, session) if params.include?("check_auth_only") return [200, "{\"success\":true}"] end return JSON.generate({ 'success' => true, 'node_list' => get_token_node_list, }) end
Compound
4
it "does not drop other indexes" do indexes[age: -1].should_not be_nil end
Class
2
it "should return :file if the request key is fully qualified" do @request.expects(:key).returns File.expand_path('/foo') @object.select_terminus(@request).should == :file end
Class
2
it "returns a random slave connection" do secondaries = [server] cluster.stub(secondaries: secondaries) secondaries.should_receive(:sample).and_return(server) cluster.socket_for(:read).should eq socket end
Class
2
def get_group_users Log.add_info(request, params.inspect) @group_id = nil if !params[:thetisBoxSelKeeper].nil? @group_id = params[:thetisBoxSelKeeper].split(':').last elsif !params[:group_id].nil? and !params[:group_id].empty? @group_id = params[:group_id] end @users = Group.get_...
Base
1
def test_update_invalid AuthSourceLdap.any_instance.stubs(:valid?).returns(false) put :update, {:id => AuthSourceLdap.first, :auth_source_ldap => {:name => AuthSourceLdap.first.name} }, set_session_user assert_template 'edit' end
Class
2
def build_query(path, details) query = @pattern.dup query.gsub!(/\:prefix(\/)?/, path.prefix.empty? ? "" : "#{path.prefix}\\1") # prefix can be empty... query.gsub!(/\:action/, path.partial? ? "_#{path.name}" : path.name) details.each do |ext, variants| query.gsub!(/\:#{ext}/, "{#{v...
Class
2
it "returns default error message for spoofed media type" do build_validator file = File.new(fixture_file("5k.png"), "rb") @dummy.avatar.assign(file) detector = mock("detector", :spoofed? => true) Paperclip::MediaTypeSpoofDetector.stubs(:using).returns(detector) @validator.validate(@dummy) ...
Base
1
def initialize(file, name) @file = file @name = name end
Base
1
def test_parse_bigger xml = <<-XML.strip_heredoc <request id="1027" creator="Iggy"> <action type="submit"> <source project="home:Iggy" package="TestPack" rev="1"/> <target project="kde4" package="mypackage"/> <options> <sourceupdate>cleanup</sourceupdate> ...
Class
2
it "generates the correct messages for a secure topic" do Jobs.run_immediately! UserActionManager.enable admin = Fabricate(:admin) cat = Fabricate(:category) cat.set_permissions(admins: :full) cat.save created_post = nil messages = MessageBus.tra...
Class
2
it 'returns success' do get "/session/email-login/#{email_token.token}" expect(response).to redirect_to("/") end
Class
2
def edit Log.add_info(request, params.inspect) date_s = params[:date] if date_s.nil? or date_s.empty? @date = Date.today date_s = @date.strftime(Schedule::SYS_DATE_FORM) else @date = Date.parse(date_s) end if params[:user_id].nil? @selected_user = @login_user els...
Base
1
def insert(documents) documents = [documents] unless documents.is_a? Array insert = Protocol::Insert.new(database.name, name, documents) database.session.with(consistency: :strong) do |session| session.execute insert end end
Class
2
it "does not activate user invited via links" do invite = Fabricate(:invite, email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:not_required]) user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White') ex...
Class
2
it "returns the socket" do cluster.stub(:sync) { cluster.servers << server } cluster.socket_for(:write).should eq socket end
Class
2
def self.get_tmpl_folder tmpl_folder = Folder.where("folders.name='#{TMPL_ROOT}'").first if tmpl_folder.nil? ary = self.setup_tmpl_folder unless ary.nil? or ary.empty? tmpl_folder = ary[0] tmpl_system_folder = ary[1] tmpl_workflows_folder = ary[2] tmpl_local_fol...
Base
1
it 'avoids xss attacks' do h = last_response.headers['X-MiniProfiler-Ids'] id = ::JSON.parse(h)[0] get "/mini-profiler-resources/results?id=%22%3E%3Cqss%3E" last_response.should_not be_ok last_response.body.should_not =~ /<qss>/ last_response.body.should =~ /&lt;qss&gt;/ end
Class
2
def Sendmail.call(path, arguments, destinations, mail) IO.popen("#{path} #{arguments} #{destinations}", "w+") do |io| io.puts mail.encoded.to_lf io.flush end end
Class
2
def set_sync_options(params, request, session) if not allowed_for_local_cluster(session, Permissions::FULL) return 403, 'Permission denied' end options = [ 'sync_thread_pause', 'sync_thread_resume', 'sync_thread_disable', 'sync_thread_enable', ] if params.keys.count { |key| options.include?(key) ...
Compound
4
it "yields all indexes on the collection" do indexes.to_a.should eq \ session[:"system.indexes"].find(ns: "moped_test.users").to_a end
Class
2
def test_update_invalid Medium.any_instance.stubs(:valid?).returns(false) put :update, {:id => Medium.first, :medium => {:name => nil}}, set_session_user assert_template 'edit' end
Class
2
def ajax_delete_items Log.add_info(request, params.inspect) folder_id = params[:id] unless params[:check_item].blank? is_admin = @login_user.admin?(User::AUTH_ITEM) count = 0 params[:check_item].each do |item_id, value| if value == '1' begin item = Item....
Base
1
def self.parse_csv_row(row, book, idxs, user) imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip) unless imp_id.nil? or imp_id.empty? org_address = Address.find_by_id(imp_id) end if org_address.nil? address = Address.new else address = org_address end ...
Base
1
def destroy Log.add_info(request, params.inspect) return unless request.post? begin Item.destroy(params[:id]) rescue => evar Log.add_error(request, evar) end if params[:from_action].nil? render(:text => params[:id]) else params.delete(:controller) params.de...
Base
1
def get_nodes_status() corosync_online = [] corosync_offline = [] pacemaker_online = [] pacemaker_offline = [] pacemaker_standby = [] in_pacemaker = false stdout, stderr, retval = run_cmd( PCSAuth.getSuperuserSession, PCS, "status", "nodes", "both" ) stdout.each {|l| l = l.chomp if l.start...
Compound
4
it "creates an index with the provided name" do indexes.create(key, name: "custom_index_name") indexes[key]["name"].should eq "custom_index_name" end
Class
2
def default_ids_hash(populate_values = false) ids = HashWithIndifferentAccess.new hash_keys.each do |col| ids[col] = populate_values ? Array(self.send(col)) : [] end ids end
Class
2
def ffi_lib(*names) raise LoadError.new("library names list must not be empty") if names.empty? lib_flags = defined?(@ffi_lib_flags) ? @ffi_lib_flags : FFI::DynamicLibrary::RTLD_LAZY | FFI::DynamicLibrary::RTLD_LOCAL ffi_libs = names.map do |name| if name == FFI::CURRENT_PROCESS ...
Base
1
def next now = Time.new.to_i counter = @mutex.synchronize do last_timestamp, @last_timestamp = @last_timestamp, now if last_timestamp == now @counter += 1 else @counter = 0 end end generate(now...
Class
2
def self.get_tree_by_group_for_admin(group_id) SqlHelper.validate_token([group_id]) folder_tree = {} tree_id = '0' if group_id.to_s == '0' sql = 'select distinct * from folders' where = " where (parent_id = #{tree_id})" where << " and ((xtype is null) or not(xtype = '#{XTYPE_GROU...
Base
1
def add_acl_role_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::GRANT) return 403, 'Permission denied' end retval = add_acl_role(session, params["name"], params["description"]) if retval == "" return [200, "Successfully added ACL role"] else return [ ...
Compound
4
it :test_render_parse_nil_param do assert_raises(ArgumentError) { parser.parse_memory(nil) } end
Base
1
def test_jail_classes_should_have_limited_methods expected = ["new", "methods", "name", "inherited", "method_added", "inspect", "allow", "allowed?", "allowed_methods", "init_allowed_methods", "<", # < needed in Rails Object#subclasses_of "ancestors", "==" # ancestor...
Class
2
def create_cluster(params, request, session) if not allowed_for_superuser(session) return 403, 'Permission denied' end if set_corosync_conf(params, request, session) cluster_start(params, request, session) else return "Failed" end end
Compound
4
it "should escape evil haxxor attemptes" do Mail.defaults do delivery_method :sendmail, :arguments => nil end mail = Mail.new do from '"foo\";touch /tmp/PWNED;\""@blah.com' to 'marcel@test.lindsaar.net' subject 'invalid RFC2822' end Mail::Sendmail.should_r...
Class
2
it "with Pathname command" do cl = subject.build_command_line(Pathname.new("/usr/bin/ruby")) expect(cl).to eq "/usr/bin/ruby" end
Base
1
def auth(params, request, session) token = PCSAuth.validUser(params['username'],params['password'], true) # If we authorized to this machine, attempt to authorize everywhere node_list = [] if token and params["bidirectional"] params.each { |k,v| if k.start_with?("node-") node_list.push(v) ...
Compound
4
def initialize(string) super("'#{string}' is not a valid object id.") end
Class
2
it "limits the query" do session.should_receive(:query) do |query| query.limit.should eq(-1) reply end session.simple_query(query) end
Class
2
it "inserts the document" do session.should_receive(:execute).with do |insert| insert.documents.should eq [{a: 1}] end collection.insert(a: 1) end
Class
2
it 'returns the right response' do get "/session/email-login/adasdad" expect(response.status).to eq(200) expect(CGI.unescapeHTML(response.body)).to match( I18n.t('email_login.invalid_token') ) end
Class
2
def setup FactoryGirl.create(:host) end
Class
2
it "sanitizes crazy params" do cl = subject.build_command_line("true", modified_params) expect(cl).to eq "true --user bob --pass P@\\$sw0\\^\\&\\ \\|\\<\\>/-\\+\\*d\\% --db --desc=Some\\ Description --symkey --symkey-dash pkg1 some\\ pkg --pool 123 --pool 456" end
Base
1
it "returns the right category group permissions for an anon user" do json = described_class.new(category, scope: Guardian.new, root: false).as_json expect(json[:group_permissions]).to eq([ { permission_type: CategoryGroup.permission_types[:full], group_name: Group[:everyone]&.name } ...
Base
1
def index @applications = Doorkeeper.config.application_model.authorized_for(current_resource_owner) respond_to do |format| format.html format.json { render json: @applications } end end
Class
2
def self.save_sync_new_tokens(config, new_tokens, nodes, cluster_name) with_new_tokens = PCSTokens.new(config.text) with_new_tokens.tokens.update(new_tokens) config_new = PcsdTokens.from_text(with_new_tokens.text) if not cluster_name or cluster_name.empty? # we run on a standalone host, no confi...
Compound
4
def edit_timecard Log.add_info(request, params.inspect) date_s = params[:date] if date_s.nil? or date_s.empty? @date = Date.today date_s = @date.strftime(Schedule::SYS_DATE_FORM) else @date = Date.parse(date_s) end @timecard = Timecard.get_for(@login_user.id, date_s) ...
Base
1
it "stores whether the connection is direct" do cluster.direct.should be_true end
Class
2
def add_constraint_rule_remote(params, request, session) if not allowed_for_local_cluster(session, Permissions::WRITE) return 403, 'Permission denied' end if params["c_type"] == "loc" retval, error = add_location_constraint_rule( session, params["res_id"], params["rule"], params["score"], para...
Compound
4
it "should allow requests that are whitelisted" do set_cookie("__profilin=stylin") get '/whitelisted' last_response.headers['X-MiniProfiler-Ids'].should_not be_nil end
Class
2
def simple_query(query) query.limit = -1 query(query).documents.first end
Class
2
def remove_node(session, new_nodename, all=false) if all # we check for a quorum loss warning in remote_remove_nodes out, stderror, retval = run_cmd( session, PCS, "cluster", "node", "remove", new_nodename, "--force" ) else out, stderror, retval = run_cmd( session, PCS, "cluster", "local...
Compound
4