repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/004_constants.rb
config/initializers/004_constants.rb
# frozen_string_literal: true GOOGLE_CLOUD_PROJECT_ID = GlobalConfig.get("GOOGLE_CLOUD_PROJECT_ID") GUMROAD_ADMIN_ID = GlobalConfig.get("GUMROAD_ADMIN_ID", Rails.env.staging? ? 978 : 767082) # admin@gumroad.com GUMROAD_STARTED_DATE = Date.parse("2011-04-04") PRODUCT_EVENT_TRACKING_STARTED_DATE = Date.parse("2012-10-13") REFERRER_DOMAIN_FOR_GUMROAD_RECOMMENDED_PRODUCTS = "recommended_by_gumroad" COMMON_REFERRERS_NAMES = { "dribbble.com" => "Dribbble", "facebook.com" => "Facebook", "google.com" => "Google", "gumroad.com" => "Gumroad", "pinterest.com" => "Pinterest", "reddit.com" => "Reddit", "shutterstock.com" => "Shutterstock", "tumblr.com" => "Tumblr", "api.twitter.com" => "Twitter", "t.co" => "Twitter", "twitter.com" => "Twitter", "youtube.com" => "Youtube" }.freeze STATES = %w[AA AE AP AL AK AZ AR CA CO CT DE FL GA HI ID IL IN IA KS KY LA ME MD MA MI MN MS MO MT NE NV NH NJ NM NY NC ND OH OK OR PA RI SC SD TN TX UT VT VA WA WV WI WY DC].freeze MILITARY_STATES = %w[AA AE AP].freeze # For about 3% of US IPs we can deduce the country but not the state. Keep track of these, and also military states, under "other" so that they're # counted towards the overall US stats. STATE_OTHER = "other" STATES_SUPPORTED_BY_ANALYTICS = STATES - MILITARY_STATES + [STATE_OTHER] QUEBEC = "QC" DENYLIST = %w[ a about account activate add admin administrator api app apps archive archives assets auth balance better blog cache cancel careers cart challenge changelog checkout codereview community compare config configuration connect contact create delete direct_messages discover documentation download downloads edit email employment enterprise facebook faq favorites feed feedback feeds fleet fleets follow followers following friend friends group groups gist help home hosting hostmaster idea ideas index info invitations invite is it json job jobs lists login logout logs mail map maps mine mis news oauth oauth_clients offers openid order orders organizations plans popular privacy projects put post read recruitment register remove replies root rss sales save search security sessions settings shop signup sitemap ssl ssladmin ssladministrator sslwebmaster status stories stream styleguide subscribe subscriptions support sysadmin sysadministrator terms tour translations trends twitter twittr update unfollow unsubscribe url user weather widget widgets wiki ww www wwww xfn xml xmpp yml yaml ladygaga kanye kanyewest randyjackson mariahcarey atrak deadmau5 avicii prettylights justinbieber calvinharris katyperry rihanna shakira barackobama kimkardashian taylorswift taylorswift13 nickiminaj oprah jtimberlake theellenshow ellen selenagomez kaka aplusk love recommended_products pay _dmarc _domainkey blog cloud-front-static-1 creators customers domains domains-staging files files-3 iffy m production-custom-domain-with-ip production-sample-shop public-files sample-shop staging staging-1 staging-2 staging-assets staging-custom-domain-with-ip staging-files staging-public-files staging-logs staging-sample-shop staging-static-1 staging-static-2 static-1 static-2 static-2-direct test-custom-domain transactions v3he4xy3rbwt].freeze INTERNET_EXCEPTIONS = [SocketError, Errno::ECONNREFUSED, Errno::ECONNRESET, Errno::ENETUNREACH, Errno::EHOSTUNREACH, Errno::EADDRNOTAVAIL, EOFError, URI::InvalidURIError, Addressable::URI::InvalidURIError, Timeout::Error, Net::HTTPBadResponse, Net::OpenTimeout, Net::ReadTimeout, OpenURI::HTTPError, OpenSSL::SSL::SSLError, Faraday::ConnectionFailed].freeze FILE_REGEX = { archive: /rar|zip|tar/i, audio: /mp3|aac|wma|wav|m4a|flac/i, epub_document: /epub/i, executable: /exe/i, document: /doc|docx|pdf|ppt|pptx/i, image: /jpeg|gif|png|jpg|tif|bmp|tiff/i, mobi_document: /mobi/i, psd_image: /psd/i, text_document: /txt|xml|json/i, video: /mp4|m4v|mov|mpeg|mpeg4|wmv|movie|ogv|avi|webm/i, word_document: /doc/i }.stringify_keys REPLICAS_HOSTS = 1.upto(3).map do |i| [ENV["DATABASE_REPLICA#{i}_HOST"], ENV["DATABASE_WORKER_REPLICA#{i}_HOST"]] end.flatten.keep_if(&:present?).uniq - [ENV["DATABASE_HOST"]] MAX_FILE_NAME_BYTESIZE = 255 # https://www.elastic.co/guide/en/elasticsearch/reference/current/search-settings.html#search-settings-max-buckets # When used in composite aggregations, it will end up determining how many times we need to paginate results. # If the queries end up taking too much memory, consider lowering this number. # This number can't be more than 65_535 (65_536 - 1 parent bucket). ES_MAX_BUCKET_SIZE = 65_535
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/discord.rb
config/initializers/discord.rb
# frozen_string_literal: true DISCORD_OAUTH_TOKEN_URL = GlobalConfig.get("DISCORD_OAUTH_TOKEN_URL", "https://discord.com/api/oauth2/token") DISCORD_GUMROAD_BOT_ID = GlobalConfig.get("DISCORD_BOT_ID", "951121634046140416") DISCORD_CLIENT_ID = GlobalConfig.get("DISCORD_CLIENT_ID") DISCORD_CLIENT_SECRET = GlobalConfig.get("DISCORD_CLIENT_SECRET") DISCORD_BOT_TOKEN = GlobalConfig.get("DISCORD_BOT_TOKEN")
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/id_headers.rb
config/initializers/id_headers.rb
# frozen_string_literal: true if Rails.env.staging? || Rails.env.production? REVISION = ENV.fetch("REVISION") else REVISION = GlobalConfig.get("REVISION_DEFAULT", "no-revision") end GR_NUM = if Rails.env.production? GlobalConfig.get("ENV_IDENTIFIER_PROD", "PROD") else GlobalConfig.get("ENV_IDENTIFIER_DEV", "DEV") end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/pdfkit.rb
config/initializers/pdfkit.rb
# frozen_string_literal: true if Rails.env.staging? || Rails.env.production? PDFKit.configure do |config| config.wkhtmltopdf = File.join("/", "usr", "local", "bin", "wkhtmltopdf") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/redis_logger.rb
config/initializers/redis_logger.rb
# frozen_string_literal: true if ENV["LOG_REDIS"] == "1" $redis.client.logger = Rails.logger end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/assets.rb
config/initializers/assets.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = "1.0" Rails.application.config.assets.digest = true # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path Rails.application.config.assets.paths << Rails.root.join("node_modules") Rails.application.config.assets.paths << Rails.root.join("app/javascript/stylesheets") Rails.application.config.assets.enabled = true Rails.application.config.assets.initialize_on_precompile = true # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in the app/assets # folder are already added. # Rails.application.config.assets.precompile += %w( admin.js admin.css )
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/active_record_schema_dumper.rb
config/initializers/active_record_schema_dumper.rb
# frozen_string_literal: true class ActiveRecord::SchemaDumper alias_method :original_index_parts, :index_parts def index_parts(index) parts = original_index_parts(index) parts[0].delete!("\\") parts end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/sidekiq_cron.rb
config/initializers/sidekiq_cron.rb
# frozen_string_literal: true Sidekiq.configure_server do |config| config.on(:startup) do sidekiq_schedule = YAML.load_file(Rails.root.join("config", "sidekiq_schedule.yml")) Sidekiq::Cron::Job.load_from_hash!(sidekiq_schedule, source: "schedule") end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/elasticsearch.rb
config/initializers/elasticsearch.rb
# frozen_string_literal: true EsClient = Elasticsearch::Model.client = Elasticsearch::Client.new( host: ENV.fetch("ELASTICSEARCH_HOST"), retry_on_failure: 5, transport_options: { request: { timeout: 5 } }, log: true ) USE_ES_ALIASES = Rails.env.production? || (Rails.env.staging? && ENV["BRANCH_DEPLOYMENT"] != "true")
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/form_tag_helper.rb
config/initializers/form_tag_helper.rb
# frozen_string_literal: true ActionView::Helpers::CsrfHelper.class_eval do def csrf_meta_tags return unless protect_against_forgery? [ tag(:meta, name: "csrf-param", content: request_forgery_protection_token), tag(:meta, name: "csrf-token", content: ApplicationController::TOKEN_PLACEHOLDER) ].join("\n").html_safe end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/reset_cloudflare_hmac_key.rb
config/initializers/reset_cloudflare_hmac_key.rb
# frozen_string_literal: true Rails.application.credentials.cloudflare_hmac_key = "sample_key" if Rails.env.test?
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/000_facebook.rb
config/initializers/000_facebook.rb
# frozen_string_literal: true FACEBOOK_APP_ID = GlobalConfig.get("FACEBOOK_APP_ID") FACEBOOK_APP_SECRET = GlobalConfig.get("FACEBOOK_APP_SECRET") FACEBOOK_OG_NAMESPACE = GlobalConfig.get("FACEBOOK_OG_NAMESPACE") FACEBOOK_API_VERSION = GlobalConfig.get("FACEBOOK_API_VERSION", "v19.0")
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/react_on_rails.rb
config/initializers/react_on_rails.rb
# frozen_string_literal: true # See https://github.com/shakacode/react_on_rails/blob/master/docs/basics/configuration.md # for many more options. module RenderingExtension extend self def custom_context(view_context) pundit_user = view_context.pundit_user { design_settings: { font: { name: "ABC Favorit", url: view_context.font_url("ABCFavorit-Regular.woff2") } }, domain_settings: { scheme: PROTOCOL, app_domain: DOMAIN, root_domain: ROOT_DOMAIN, short_domain: SHORT_DOMAIN, discover_domain: DISCOVER_DOMAIN, third_party_analytics_domain: THIRD_PARTY_ANALYTICS_DOMAIN, api_domain: API_DOMAIN, }, user_agent_info: { is_mobile: view_context.controller.is_mobile?, }, logged_in_user: logged_in_user_props(pundit_user, is_impersonating: view_context.controller.impersonating?), current_seller: current_seller_props(pundit_user), csp_nonce: SecureHeaders.content_security_policy_script_nonce(view_context.request), locale: view_context.controller.http_accept_language.user_preferred_languages[0] || "en-US", feature_flags: { require_email_typo_acknowledgment: Feature.active?(:require_email_typo_acknowledgment), } } end private def logged_in_user_props(pundit_user, is_impersonating:) user = pundit_user.user return nil unless user { id: user.external_id, email: user.email, name: user.name, avatar_url: user.avatar_url, confirmed: user.confirmed?, team_memberships: UserMembershipsPresenter.new(pundit_user:).props, policies: policies_props(pundit_user), is_gumroad_admin: user.is_team_member?, is_impersonating:, lazy_load_offscreen_discover_images: Feature.active?(:lazy_load_offscreen_discover_images, user), } end # Policies accessible via loggedInUser # Only used for policies that don't need record-specific logic, like LinkPolicy::edit? where a product record is required # Policies should be grouped by Policy class name # Naming convention: # - policy class key: Settings::Payments::UserPolicy.name.underscore.tr("/", "_").gsub(/(_policy)$/, "") # - policy method key: Settings::Payments::UserPolicy.instance_methods(false).first.to_s.chop # def policies_props(pundit_user) { affiliate_requests_onboarding_form: { update: Pundit.policy!(pundit_user, [:affiliate_requests, :onboarding_form]).update?, }, direct_affiliate: { create: Pundit.policy!(pundit_user, DirectAffiliate).create?, update: Pundit.policy!(pundit_user, DirectAffiliate).update?, }, collaborator: { create: Pundit.policy!(pundit_user, Collaborator).create?, update: Pundit.policy!(pundit_user, Collaborator).update?, }, product: { create: Pundit.policy!(pundit_user, Link).create?, }, product_review_response: { update: Pundit.policy!(pundit_user, ProductReviewResponse).update?, }, balance: { index: Pundit.policy!(pundit_user, :balance).index?, export: Pundit.policy!(pundit_user, :balance).export?, }, checkout_offer_code: { create: Pundit.policy!(pundit_user, [:checkout, OfferCode]).create?, }, checkout_form: { update: Pundit.policy!(pundit_user, [:checkout, :form]).update?, }, upsell: { create: Pundit.policy!(pundit_user, [:checkout, Upsell]).create?, }, settings_payments_user: { show: Pundit.policy!(pundit_user, [:settings, :payments, pundit_user.seller]).show?, }, settings_profile: { manage_social_connections: Pundit.policy!(pundit_user, [:settings, :profile]).manage_social_connections?, update: Pundit.policy!(pundit_user, [:settings, :profile]).update?, update_username: Pundit.policy!(pundit_user, [:settings, :profile]).update_username? }, settings_third_party_analytics_user: { update: Pundit.policy!(pundit_user, [:settings, :third_party_analytics, pundit_user.seller]).update? }, installment: { create: Pundit.policy!(pundit_user, Installment).create?, }, workflow: { create: Pundit.policy!(pundit_user, Workflow).create?, }, utm_link: { index: Pundit.policy!(pundit_user, :utm_link).index?, }, community: { index: Pundit.policy!(pundit_user, Community).index?, } } end def current_seller_props(pundit_user) seller = pundit_user.seller return nil unless seller UserPresenter.new(user: pundit_user.seller).as_current_seller end end ReactOnRails.configure do |config| # This configures the script to run to build the production assets by webpack. Set this to nil # if you don't want react_on_rails building this file for you. # If nil, then the standard shakacode/shakapacker assets:precompile will run # config.build_production_command = nil ################################################################################ ################################################################################ # TEST CONFIGURATION OPTIONS # Below options are used with the use of this test helper: # ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config) ################################################################################ # If you are using this in your spec_helper.rb (or rails_helper.rb): # # ReactOnRails::TestHelper.configure_rspec_to_compile_assets(config) # # with rspec then this controls what yarn command is run # to automatically refresh your webpack assets on every test run. # # Alternately, you can remove the `ReactOnRails::TestHelper.configure_rspec_to_compile_assets` # and set the config/shakapacker.yml option for test to true. config.build_test_command = "RAILS_ENV=test bin/shakapacker" ################################################################################ ################################################################################ # SERVER RENDERING OPTIONS ################################################################################ # This is the file used for server rendering of React when using `(prerender: true)` # If you are never using server rendering, you should set this to "". # Note, there is only one server bundle, unlike JavaScript where you want to minimize the size # of the JS sent to the client. For the server rendering, React on Rails creates a pool of # JavaScript execution instances which should handle any component requested. # # While you may configure this to be the same as your client bundle file, this file is typically # different. You should have ONE server bundle which can create all of your server rendered # React components. # config.server_bundle_js_file = "js/ssr.js" config.rendering_extension = RenderingExtension end module ReactOnRails::Helper alias_method :original_react_component, :react_component def react_component(name, opts = {}) opts[:html_options] ||= {} opts[:html_options][:class] = "react-entry-point" opts[:html_options][:style] = "display:contents" opts[:request] = request original_react_component(name, opts) end alias_method :original_internal_react_component, :internal_react_component def internal_react_component(*args) result = original_internal_react_component(*args) if result[:result]["redirect"] controller.redirect_to result[:result]["redirect"] end html = result[:result]["html"] if html.end_with? "</script>" html.insert(html.rindex("<script") + 7, " data-cfasync=\"false\"") end nonce = SecureHeaders.content_security_policy_script_nonce(request) # react-on-rails does not provide a way to set a nonce replay = result[:result]["consoleReplayScript"] replay["<script"] = "<script nonce='#{nonce}'" if replay.present? result end end module ReactOnRails module ServerRenderingJsCode class << self def render(props_string, rails_context, _, react_component_name, _) # This is mostly copied from the original, with additions to handle Promises, the fetch wrapper, # and to pass additional options. <<-JS (function() { Response.prototype.body = ""; globalThis.fetch = (url, settings) => { const res = _fetch(url, settings); return new Response(res.body, res); }; return ReactOnRails.serverRenderReactComponent({ name: '#{react_component_name}', props: #{props_string}, railsContext: #{rails_context}, renderingReturnsPromises: true, throwJsErrors: true, }); })().then( (res) => finish(JSON.stringify(res)), (e) => { if (e instanceof Response) finish(JSON.stringify({ redirect: e.headers.get("Location"), consoleReplayScript: "", html: "" })); else finish(JSON.stringify({ __error: e.stack })); }) JS end end end end class ReactRuntime < ExecJS::MiniRacerRuntime class Context < ExecJS::MiniRacerRuntime::Context def initialize(*args) super @context.attach "_fetch", proc { |url, settings| # We intercept the frontend's calls to `fetch` and call the controllers here directly uri = URI.parse(url) url = "#{UrlService.domain_with_protocol}#{url}" if uri.is_a? URI::Generic query_params = Rack::Utils.parse_nested_query(uri.query) res = Rails.application.routes.recognize_path(url, method: settings["method"]) response = ActionDispatch::Response.create controller = "#{res[:controller].camelize}Controller".constantize.new controller.request = @request controller.response = response params = res params = params.merge(settings["body"]) if settings["body"].is_a? Hash params = params.merge(query_params) controller.params = params controller.process(res[:action]) { body: response.body, status: response.status, headers: response.headers } } @context.attach "finish", proc { |value| @value = value } # Once the bundle has been evaluated, we monkey-patch the eval method to handle Promises instead. # Since mini-racer does not provide any native promise handling, we simply spin-wait until we've received a response. class << self def eval(code, options) @value = nil @request = options.internal_option(:request) original_eval(code) 1000.times do sleep 0.005 unless @value end if @value json = JSON.parse(@value) raise StandardError, json["__error"] if json["__error"] end @value end end end alias_method :original_eval, :eval end end module ReactOnRails::ServerRenderingPool # Monkey-patch a replacement for ExecJS into ReactOnRails so we don't have to modify it globally ExecJS = ReactRuntime.new class RubyEmbeddedJavaScript # Copied from the original, but passes through the options. class << self def eval_js(js_code, render_options) @js_context_pool.with do |js_context| js_context.eval(js_code, render_options) end end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/taxjar.rb
config/initializers/taxjar.rb
# frozen_string_literal: true # TaxJar gives us two API keys: one for Sandbox, and one for Live. # We're using the Live key in production, and the Sandbox key everywhere else. TAXJAR_API_KEY = GlobalConfig.get("TAXJAR_API_KEY") if Rails.env.production? TAXJAR_ENDPOINT = "https://api.taxjar.com" else TAXJAR_ENDPOINT = "https://api.sandbox.taxjar.com" end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/sprockets.rb
config/initializers/sprockets.rb
# frozen_string_literal: true # Work around a segfault during assets compilation # https://github.com/sass/sassc-ruby/issues/207#issuecomment-674626874 Sprockets.export_concurrent = false
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/rpush.rb
config/initializers/rpush.rb
# frozen_string_literal: true Rpush.configure do |config| # Supported clients are :active_record and :redis config.client = :redis # Options passed to Redis.new config.redis_options = { url: "redis://#{ENV["RPUSH_REDIS_HOST"]}" } # Frequency in seconds to check for new notifications. config.push_poll = 2 # The maximum number of notifications to load from the store every `push_poll` seconds. # If some notifications are still enqueued internally, Rpush will load the batch_size less # the number enqueued. An exception to this is if the service is able to receive multiple # notification payloads over the connection with a single write, such as APNs. config.batch_size = 100 # Path to write PID file. Relative to current directory unless absolute. config.pid_file = Rails.root.join("tmp", "rpush.pid").to_s # Path to log file. Relative to current directory unless absolute. config.log_file = Rails.root.join("log", "rpush.log").to_s config.log_level = (defined?(Rails) && Rails.logger) ? Rails.logger.level : ::Logger::Severity::INFO # Define a custom logger. config.logger = (defined?(Rails) && Rails.logger) ? Rails.logger : ::Logger.new(STDOUT) end Rpush.reflect do |on| # Called with a Rpush::Apns::Feedback instance when feedback is received # from the APNs that a notification has failed to be delivered. # Further notifications should not be sent to the device. on.apns_feedback do |feedback| CleanupRpushDeviceService.new(feedback).process end # Called when a notification is queued internally for delivery. # The internal queue for each app runner can be inspected: # # Rpush::Daemon::AppRunner.runners.each do |app_id, runner| # runner.app # runner.queue_size # end # # on.notification_enqueued do |notification| # end def logger Rpush.config.logger end # Called when a notification is successfully delivered. on.notification_delivered do |notification| logger.info "Delivered notification #{notification.id} to #{notification.device_token} with message #{notification.alert}" Modis.with_connection do |redis| redis.expire(notification.key, 48.hours.to_i) redis.srem("rpush:notifications:all", notification.id) end end # Called when notification delivery failed. # Call 'error_code' and 'error_description' on the notification for the cause. on.notification_failed do |notification| logger.info "Delivery failed for notification #{notification.id} (#{notification.error_code} / #{notification.error_description})" Modis.with_connection do |redis| redis.expire(notification.key, 24.hours.to_i) redis.srem("rpush:notifications:all", notification.id) end end # Called when the notification delivery failed and only the notification ID # is present in memory. # on.notification_id_failed do |app, notification_id, error_code, error_description| # end # Called when a notification will be retried at a later date. # Call 'deliver_after' on the notification for the next delivery date # and 'retries' for the number of times this notification has been retried. # on.notification_will_retry do |notification| # end # Called when a notification will be retried and only the notification ID # is present in memory. # on.notification_id_will_retry do |app, notification_id, retry_after| # end # Called when a TCP connection is lost and will be reconnected. # on.tcp_connection_lost do |app, error| # end # Called for each recipient which successfully receives a notification. This # can occur more than once for the same notification when there are multiple # recipients. # on.gcm_delivered_to_recipient do |notification, registration_id| # end # Called for each recipient which fails to receive a notification. This # can occur more than once for the same notification when there are multiple # recipients. (do not handle invalid registration IDs here) # on.gcm_failed_to_recipient do |notification, error, registration_id| # end # Called when the GCM returns a canonical registration ID. # You will need to replace old_id with canonical_id in your records. # on.gcm_canonical_id do |old_id, canonical_id| # end # Called when the GCM returns a failure that indicates an invalid registration id. # You will need to delete the registration_id from your records. # on.gcm_invalid_registration_id do |app, error, registration_id| # end # Called when an SSL certificate will expire within 1 month. # Implement on.error to catch errors raised when the certificate expires. on.ssl_certificate_will_expire do |app, expiration_time| Bugsnag.notify(StandardError.new("App Certificate is about to expire soon #{expiration_time}")) end # Called when an SSL certificate has been revoked. on.ssl_certificate_revoked do |app, error| Bugsnag.notify(StandardError.new("App Certificate has been revoked #{error}")) end # Called when the ADM returns a canonical registration ID. # You will need to replace old_id with canonical_id in your records. # on.adm_canonical_id do |old_id, canonical_id| # end # Called when Failed to deliver to ADM. Check the 'reason' string for further # explanations. # # If the reason is the string 'Unregistered', you should remove # this registration id from your records. # on.adm_failed_to_recipient do |notification, registration_id, reason| # end # Called when Failed to deliver to WNS. Check the 'reason' string for further # explanations. # You should remove this uri from your records # on.wns_invalid_channel do |notification, uri, reason| # end # Called when an exception is raised. # on.error do |error| # end end # The rpush daemon needs all rpush apps to be present in Redis at start up. # (See https://github.com/gumroad/web/pull/11372#discussion_r329752185) if ENV["INITIALIZE_RPUSH_APPS"] Rails.application.config.after_initialize do PushNotificationService::Ios.creator_app PushNotificationService::Ios.consumer_app PushNotificationService::Android.consumer_app end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/united_states_zip_codes.rb
config/initializers/united_states_zip_codes.rb
# frozen_string_literal: true # Known zip codes that don't show up in the US Zip Codes database. KNOWN_ZIP_CODES = { "85144" => "AZ" } # The United States Zip Codes website recommends that we update this file annually. https://www.unitedstateszipcodes.org/zip-code-database/ # Changes to 5-digit zip codes are infrequent. Instead of taking on an API dependency, we use this source of truth. # See `CleanUsZipCodeDatabaseFile` for information on how to update this file. ZIP_CODE_TO_STATE = CSV.parse(File.read("#{Rails.root}/config/zip_code_database.csv")).drop(1).map! { |row| [row[0], row[1]] }.to_h.merge(KNOWN_ZIP_CODES)
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/hash.rb
config/initializers/hash.rb
# frozen_string_literal: true class Hash def deep_reject!(&block) reject! do |key, value| value.deep_reject!(&block) if value.is_a?(Hash) yield(key, value) end self end def deep_values_strip! transform_values! do |value| if value.is_a?(String) value.strip elsif value.is_a?(Hash) value.deep_values_strip! else value end end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/custom_domain.rb
config/initializers/custom_domain.rb
# frozen_string_literal: true if Rails.env.production? CUSTOM_DOMAIN_CNAME = GlobalConfig.get("CUSTOM_DOMAIN_CNAME_PROD", "domains.gumroad.com") # CUSTOM_DOMAIN_STATIC_IP_HOST is for internal use. It will be used only to # check if the custom domain is pointed to the static IP address. CUSTOM_DOMAIN_STATIC_IP_HOST = GlobalConfig.get("CUSTOM_DOMAIN_STATIC_IP_HOST_PROD", "production-custom-domains-static-ip.gumroad.net") else CUSTOM_DOMAIN_CNAME = GlobalConfig.get("CUSTOM_DOMAIN_CNAME_STAGING", "domains-staging.gumroad.com") CUSTOM_DOMAIN_STATIC_IP_HOST = GlobalConfig.get("CUSTOM_DOMAIN_STATIC_IP_HOST_STAGING", "staging-custom-domains-static-ip.gumroad.net") end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/backtrace_silencers.rb
config/initializers/backtrace_silencers.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| /my_noisy_library/.match?(line) } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code # by setting BACKTRACE=1 before calling your invocation, like "BACKTRACE=1 ./bin/rails runner 'MyClass.perform'". Rails.backtrace_cleaner.remove_silencers! if ENV["BACKTRACE"]
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/mime_types.rb
config/initializers/mime_types.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf # Mime::Type.register_alias "text/html", :iphone Mime::Type.register "image/svg+xml", :svg Mime::Type.register "application/smil+xml", :smil Mime::Type.register "application/x-mpegurl", :m3u8 # TODO remove this when rack is updated to v3 Rack::Mime::MIME_TYPES[".mjs"] = "text/javascript"
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/003_stripe.rb
config/initializers/003_stripe.rb
# frozen_string_literal: true Stripe.api_version = Rails.env.test? ? "2023-10-16" : "2023-10-16; risk_in_requirements_beta=v1; retrieve_tax_forms_beta=v1;" # Ref: https://github.com/gumroad/web/issues/17770, https://stripe.com/docs/rate-limits#object-lock-timeouts Stripe.max_network_retries = 3 if Rails.env.production? STRIPE_PUBLIC_KEY = GlobalConfig.get("STRIPE_PUBLIC_KEY_PROD", "pk_live_Db80xIzLPWhKo1byPrnERmym") else STRIPE_PUBLIC_KEY = GlobalConfig.get("STRIPE_PUBLIC_KEY_TEST", "pk_test_ehGPKw3JPRHYiqEEjgJ02ULC") end Stripe.api_key = GlobalConfig.get("STRIPE_API_KEY") STRIPE_PLATFORM_ACCOUNT_ID = GlobalConfig.get("STRIPE_PLATFORM_ACCOUNT_ID") STRIPE_CONNECT_CLIENT_ID = GlobalConfig.get("STRIPE_CONNECT_CLIENT_ID") STRIPE_SECRET = GlobalConfig.get("STRIPE_API_KEY")
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/rack_attack.rb
config/initializers/rack_attack.rb
# frozen_string_literal: true class Rack::Attack redis_url = ENV.fetch("RACK_ATTACK_REDIS_HOST") redis_client = Redis.new(url: "redis://#{redis_url}") Rack::Attack.cache.store = Rack::Attack::StoreProxy::RedisStoreProxy.new(redis_client) class Request < ::Rack::Request # When the server is behind a load balancer def remote_ip @remote_ip ||= (env["HTTP_CF_CONNECTING_IP"] || env["action_dispatch.remote_ip"] || ip).to_s end def localhost? remote_ip == "127.0.0.1" || remote_ip == "::1" end def json_params @json_params ||= begin JSON.parse(body.read) rescue {} ensure body.rewind end end end def self.matches_path?(path:, request:) if path.is_a?(Regexp) request.path.match?(path) else request.path == path end end def self.throttle_identifier(path:, method:, request:, identifier:) identifier = path.is_a?(Regexp) ? "#{request.path}:#{identifier}" : identifier if matches_path?(path:, request:) return if method.present? && request.request_method.to_s.upcase != method.to_s.upcase identifier end end def self.throttle_name(prefix:, path:, method:) name = "#{prefix}:#{path}" method.present? ? "#{name}:#{method}" : name end def self.throttle_with_exponential_backoff(name:, requests:, period:, max_level: 5, &block_proc) block = Proc.new do |req| block_proc.call(req) rescue Rack::QueryParser::InvalidParameterError # Looks like this request contains invalid params. We already have an # "invalid_params" throttle rule defined below, therefore, we don't need # to throttle it here again. # Also, this request will be passed down the middleware hierarchy. Thus # to prevent this exception from polluting our error reporting tool # we will gracefully handle it in the CatchBadRequestErrors middleware. nil end throttle(name, limit: requests, period:, &block) rpm = (requests / period.to_f) * 60 (2..max_level).each do |level| throttle("#{name}/#{level}", limit: (rpm * level), period: (8**level).seconds, &block) end end # Throttle by both IP and request parameters def self.throttle_by_ip_and_params(path:, requests:, period:, throttle_params:, method: nil) block_proc = proc { |req| throttle_identifier(path:, method:, request: req, identifier: "#{req.remote_ip}:#{throttle_params.call(req)}") } name = throttle_name(prefix: "/ip/params", path:, method:) throttle_with_exponential_backoff(name:, requests:, period:, max_level: 6, &block_proc) end # Throttle by request parameters def self.throttle_by_params(path:, requests:, period:, throttle_params:, method: nil) block_proc = proc { |req| throttle_identifier(path:, method:, request: req, identifier: "#{throttle_params.call(req)}") } name = throttle_name(prefix: "/params", path:, method:) throttle_with_exponential_backoff(name:, requests:, period:, max_level: 6, &block_proc) end # Throttle by IP with exponential backoff def self.throttle_by_ip(path:, requests:, period:, max_level: 5, method: nil) block_proc = proc { |req| throttle_identifier(path:, method:, request: req, identifier: req.remote_ip) } name = throttle_name(prefix: "/ip", path:, method:) throttle_with_exponential_backoff(name:, requests:, period:, max_level:, &block_proc) end # Throttle by IP without exponential backoff def self.throttle_by_ip_for_period(path:, requests:, period:, method: nil) name = throttle_name(prefix: "/ip/period", path:, method:) throttle(name, limit: requests, period:) do |req| throttle_identifier(path:, method:, request: req, identifier: req.remote_ip) end end # Throttle requests containing invalid params # Throttle rate: 5rpm, 30 requests/3 days, max 35 requests/24 days throttle_with_exponential_backoff( name: "invalid_params", requests: 5, period: 60.seconds, max_level: 7 ) do |req| req.params # test that params are valid false rescue Rack::QueryParser::InvalidParameterError "#{req.path}:#{req.remote_ip}" end # Disable throttling for frequently used paths in staging if Rails.env.production? throttle_by_ip path: "/login", method: :post, requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/login.json", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/signup", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/signup.json", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/follow", method: :post, requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/follow_from_embed_form", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/forgot_password.json", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/forgot_password", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip path: "/users/auth/facebook", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours # Don't allow spammer to send confirmation emails to many random emails throttle_by_ip path: "/settings", requests: 3, period: 20.seconds, method: :put # Initial: 9rpm, Max: 45 requests/9 hours end throttle_by_ip path: "/", requests: 60, period: 30.seconds # Initial: 120rpm, Max: 600 requests/9 hours throttle_by_ip path: "/api/mobile/purchases/index.json", requests: 60, period: 30.seconds # Initial: 120rpm, Max: 600 requests/9 hours throttle_by_ip path: "/mobile/purchases/index.json", requests: 60, period: 30.seconds # Initial: 120rpm, Max: 600 requests/9 hours throttle_by_ip path: "/discover", requests: 60, period: 30.seconds # Initial: 120rpm, Max: 600 requests/9 hours throttle_by_ip path: "/discover_search", requests: 60, period: 30.seconds # Initial: 120rpm, Max: 600 requests/9 hours throttle_by_ip path: "/offer_codes/compute_discount", requests: 60, period: 30.seconds # Initial: 120rpm, Max: 600 requests/9 hours throttle_by_ip path: "/purchases", requests: 40, period: 60.seconds # Initial: 40rpm, Max: 200 requests/9 hours throttle_by_ip path: "/stripe/setup_intents", requests: 40, period: 60.seconds # Initial: 40rpm, Max: 200 requests/9 hours throttle_by_ip path: "/settings/credit_card", requests: 3, period: 20.seconds # Initial: 9rpm, Max: 45 requests/9 hours throttle_by_ip_for_period path: "/purchases", requests: 50, period: 1.hour throttle_by_ip path: "/oauth/token", requests: 3000, period: 60.seconds # Initial: 3000rpm, Max: 15000 requests/9 hours # Spammers have been abusing follower's endpoints. This degrades our email reputation since we send confirmation email to each follower. # The following rules impose stricter and per-creator rate-limiting to prevent spammers from creating followers through a distributed attack. # Please see https://git.io/JfiDY for more information. # # Initial: 3rpm, Max: 18 requests/3 days (per creator, per IP) throttle_by_ip_and_params path: "/follow", requests: 3, method: :post, period: 60.seconds, throttle_params: Proc.new { |req| req.params["seller_id"] } # Initial: 3rpm, Max: 18 requests/3 days (per creator, per IP) throttle_by_ip_and_params path: "/follow_from_embed_form", requests: 3, period: 60.seconds, throttle_params: Proc.new { |req| req.params["seller_id"] } # Initial: 10rpm, Max: 60 requests/3 days (per user) throttle_by_params path: "/two-factor.json", requests: 10, method: :post, period: 60.seconds, throttle_params: Proc.new { |req| req.params["user_id"] } # Initial: 10rpm, Max: 60 requests/3 days (per user) throttle_by_params path: "/two-factor/resend_authentication_token.json", requests: 10, method: :post, period: 60.seconds, throttle_params: Proc.new { |req| req.params["user_id"] } # Initial: 10rpm, Max: 60 requests/3 days (per user) throttle_by_params path: "/two-factor/verify.html", requests: 10, period: 60.seconds, throttle_params: Proc.new { |req| req.params["user_id"] } # Initial: 4rpm, Max: 24 requests/9 hours throttle_by_params path: "/forgot_password.json", method: :post, requests: 4, period: 60.seconds, throttle_params: Proc.new { |req| req.json_params.is_a?(Hash) && req.json_params.dig("user", "email").presence } # Initial: 4rpm, Max: 24 requests/9 hours throttle_by_params path: "/forgot_password", method: :post, requests: 4, period: 60.seconds, throttle_params: Proc.new { |req| req.json_params.is_a?(Hash) && req.json_params.dig("user", "email").presence } # Throttle requests to Sales API with slow pagination throttle("/api/v2/sales", limit: 10, period: 1.second) do |req| req.remote_ip if req.path.ends_with?("/v2/sales") && req.params["page"].to_i > 10 end # Throttle POST requests to /login by login param # # Key: "rack::attack:#{Time.now.to_i/:period}:logins/login:#{req.login}" # # Note: This creates a problem where a malicious user could intentionally # throttle logins for another user and force their login requests to be # denied, but that's not very common and shouldn't happen to you. (Knock # on wood!) throttle("logins/login", limit: 3, period: 20.seconds) do |req| if req.path == "/login.json" && req.post? # return the login if present, nil otherwise req.params["user"] && req.params["user"]["login"].presence end end # Throttle POST requests to /:username/affiliate_requests # # Initial: 10rpm, Max: 50 requests/9 hours throttle_by_ip path: /\A\/[[:alnum:]]+\/affiliate_requests\z/, method: :post, requests: 10, period: 60.seconds # Throttle comment requests on posts # # Initial: 5rpm, Max: 25 requests/9 hours (per post, per IP) throttle_by_ip path: /\A\/posts\/.+\/comments\z/, method: :post, requests: 5, period: 60.seconds # Initial: 5rpm, Max: 25 requests/9 hours (per post, per IP) throttle_by_ip path: /\A\/posts\/.+\/comments\/.+\z/, method: :put, requests: 5, period: 60.seconds # Throttle requests to resend receipts # Initial: 2rpm, Max: 20 requests/9 hours (per purchase, per IP) throttle_by_ip path: /\A\/(purchases|service_charges)\/.+\/resend_receipt\z/, method: :post, requests: 2, period: 60.seconds # Throttle community chat messages # 60 requests per 60 seconds (per community, per IP) throttle_by_ip_for_period path: /\A\/internal\/communities\/.*\/chat_messages\z/, method: :post, requests: 60, period: 60.seconds # Throttle AI product details generation requests # 10 requests per 60 seconds (per IP) throttle_by_ip_for_period path: "/internal/ai_product_details_generations", method: :post, requests: 10, period: 60.seconds # Throttle ACME challenge requests # 120 requests per 60 seconds (per IP) throttle_by_ip_for_period path: /\A\/\.well-known\/acme-challenge\//, requests: 120, period: 60.seconds # Do not throttle for health check requests safelist("allow from localhost", &:localhost?) end # Log blocked events ActiveSupport::Notifications.subscribe(/throttle.rack_attack/) do |_name, _start, _finish, _request_id, payload| req = payload[:request] if req.env["rack.attack.match_type"] == :throttle request_headers = { "CF-RAY" => req.env["HTTP_CF_RAY"], "X-Amzn-Trace-Id" => req.env["HTTP_X_AMZN_TRACE_ID"] } Rails.logger.info "[Rack::Attack][Blocked] remote_ip: \"#{req.remote_ip}\", path: \"#{req.path}\", headers: #{request_headers.inspect}" end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/discover_meta_tags.rb
config/initializers/discover_meta_tags.rb
# frozen_string_literal: true DISCOVER_META_TAGS = YAML.load_file("#{Rails.root}/config/discover_meta_tags.yml").freeze
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/tagged_logging.rb
config/initializers/tagged_logging.rb
# frozen_string_literal: true Rails.application.config.log_tags = %i[subdomain uuid]
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/new_framework_defaults_7_1.rb
config/initializers/new_framework_defaults_7_1.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # # This file eases your Rails 7.1 framework defaults upgrade. # # Uncomment each configuration one by one to switch to the new default. # Once your application is ready to run with all new defaults, you can remove # this file and set the `config.load_defaults` to `7.1`. # # Read the Guide for Upgrading Ruby on Rails for more info on each option. # https://guides.rubyonrails.org/upgrading_ruby_on_rails.html ### # No longer add autoloaded paths into `$LOAD_PATH`. This means that you won't be able # to manually require files that are managed by the autoloader, which you shouldn't do anyway. # # This will reduce the size of the load path, making `require` faster if you don't use bootsnap, or reduce the size # of the bootsnap cache if you use it. # # To set this configuration, add the following line to `config/application.rb` (NOT this file): # config.add_autoload_paths_to_load_path = false ### # Remove the default X-Download-Options headers since it is used only by Internet Explorer. # If you need to support Internet Explorer, add back `"X-Download-Options" => "noopen"`. #++ Rails.application.config.action_dispatch.default_headers = { "X-Frame-Options" => "SAMEORIGIN", "X-XSS-Protection" => "0", "X-Content-Type-Options" => "nosniff", "X-Permitted-Cross-Domain-Policies" => "none", "Referrer-Policy" => "strict-origin-when-cross-origin" } ### # Do not treat an `ActionController::Parameters` instance # as equal to an equivalent `Hash` by default. #++ Rails.application.config.action_controller.allow_deprecated_parameters_hash_equality = false ### # Active Record Encryption now uses SHA-256 as its hash digest algorithm. # # There are 3 scenarios to consider. # # 1. If you have data encrypted with previous Rails versions, and you have # +config.active_support.key_generator_hash_digest_class+ configured as SHA1 (the default # before Rails 7.0), you need to configure SHA-1 for Active Record Encryption too: #++ # Rails.application.config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA1 # # 2. If you have +config.active_support.key_generator_hash_digest_class+ configured as SHA256 (the new default # in 7.0), then you need to configure SHA-256 for Active Record Encryption: #++ # Rails.application.config.active_record.encryption.hash_digest_class = OpenSSL::Digest::SHA256 # # 3. If you don't currently have data encrypted with Active Record encryption, you can disable this setting to # configure the default behavior starting 7.1+: #++ Rails.application.config.active_record.encryption.support_sha1_for_non_deterministic_encryption = false ### # No longer run after_commit callbacks on the first of multiple Active Record # instances to save changes to the same database row within a transaction. # Instead, run these callbacks on the instance most likely to have internal # state which matches what was committed to the database, typically the last # instance to save. #++ # Rails.application.config.active_record.run_commit_callbacks_on_first_saved_instances_in_transaction = false ### # Configures SQLite with a strict strings mode, which disables double-quoted string literals. # # SQLite has some quirks around double-quoted string literals. # It first tries to consider double-quoted strings as identifier names, but if they don't exist # it then considers them as string literals. Because of this, typos can silently go unnoticed. # For example, it is possible to create an index for a non existing column. # See https://www.sqlite.org/quirks.html#double_quoted_string_literals_are_accepted for more details. #++ Rails.application.config.active_record.sqlite3_adapter_strict_strings_by_default = true ### # Disable deprecated singular associations names. #++ Rails.application.config.active_record.allow_deprecated_singular_associations_name = false ### # Enable the Active Job `BigDecimal` argument serializer, which guarantees # roundtripping. Without this serializer, some queue adapters may serialize # `BigDecimal` arguments as simple (non-roundtrippable) strings. # # When deploying an application with multiple replicas, old (pre-Rails 7.1) # replicas will not be able to deserialize `BigDecimal` arguments from this # serializer. Therefore, this setting should only be enabled after all replicas # have been successfully upgraded to Rails 7.1. #++ Rails.application.config.active_job.use_big_decimal_serializer = true ### # Specify if an `ArgumentError` should be raised if `Rails.cache` `fetch` or # `write` are given an invalid `expires_at` or `expires_in` time. # Options are `true`, and `false`. If `false`, the exception will be reported # as `handled` and logged instead. #++ Rails.application.config.active_support.raise_on_invalid_cache_expiration_time = true ### # Specify whether Query Logs will format tags using the SQLCommenter format # (https://open-telemetry.github.io/opentelemetry-sqlcommenter/), or using the legacy format. # Options are `:legacy` and `:sqlcommenter`. #++ # Rails.application.config.active_record.query_log_tags_format = :sqlcommenter ### # Specify the default serializer used by `MessageEncryptor` and `MessageVerifier` # instances. # # The legacy default is `:marshal`, which is a potential vector for # deserialization attacks in cases where a message signing secret has been # leaked. # # In Rails 7.1, the new default is `:json_allow_marshal` which serializes and # deserializes with `ActiveSupport::JSON`, but can fall back to deserializing # with `Marshal` so that legacy messages can still be read. # # In Rails 7.2, the default will become `:json` which serializes and # deserializes with `ActiveSupport::JSON` only. # # Alternatively, you can choose `:message_pack` or `:message_pack_allow_marshal`, # which serialize with `ActiveSupport::MessagePack`. `ActiveSupport::MessagePack` # can roundtrip some Ruby types that are not supported by JSON, and may provide # improved performance, but it requires the `msgpack` gem. # # For more information, see # https://guides.rubyonrails.org/v7.1/configuring.html#config-active-support-message-serializer # # If you are performing a rolling deploy of a Rails 7.1 upgrade, wherein servers # that have not yet been upgraded must be able to read messages from upgraded # servers, first deploy without changing the serializer, then set the serializer # in a subsequent deploy. #++ Rails.application.config.active_support.message_serializer = :json_allow_marshal ### # Enable a performance optimization that serializes message data and metadata # together. This changes the message format, so messages serialized this way # cannot be read by older versions of Rails. However, messages that use the old # format can still be read, regardless of whether this optimization is enabled. # # To perform a rolling deploy of a Rails 7.1 upgrade, wherein servers that have # not yet been upgraded must be able to read messages from upgraded servers, # leave this optimization off on the first deploy, then enable it on a # subsequent deploy. #++ Rails.application.config.active_support.use_message_serializer_for_metadata = true ### # Set the maximum size for Rails log files. # # `config.load_defaults 7.1` does not set this value for environments other than # development and test. #++ if Rails.env.local? Rails.application.config.log_file_size = 100 * 1024 * 1024 end ### # Enable raising on assignment to attr_readonly attributes. The previous # behavior would allow assignment but silently not persist changes to the # database. #++ Rails.application.config.active_record.raise_on_assign_to_attr_readonly = true ### # Enable validating only parent-related columns for presence when the parent is mandatory. # The previous behavior was to validate the presence of the parent record, which performed an extra query # to get the parent every time the child record was updated, even when parent has not changed. #++ # Rails.application.config.active_record.belongs_to_required_validates_foreign_key = false ### # Enable precompilation of `config.filter_parameters`. Precompilation can # improve filtering performance, depending on the quantity and types of filters. #++ Rails.application.config.precompile_filter_parameters = true ### # Enable before_committed! callbacks on all enrolled records in a transaction. # The previous behavior was to only run the callbacks on the first copy of a record # if there were multiple copies of the same record enrolled in the transaction. #++ Rails.application.config.active_record.before_committed_on_all_records = true ### # Disable automatic column serialization into YAML. # To keep the historic behavior, you can set it to `YAML`, however it is # recommended to explicitly define the serialization method for each column # rather than to rely on a global default. #++ Rails.application.config.active_record.default_column_serializer = nil ### # Enable a performance optimization that serializes Active Record models # in a faster and more compact way. # # To perform a rolling deploy of a Rails 7.1 upgrade, wherein servers that have # not yet been upgraded must be able to read caches from upgraded servers, # leave this optimization off on the first deploy, then enable it on a # subsequent deploy. #++ Rails.application.config.active_record.marshalling_format_version = 7.1 ### # Run `after_commit` and `after_*_commit` callbacks in the order they are defined in a model. # This matches the behaviour of all other callbacks. # In previous versions of Rails, they ran in the inverse order. #++ # Rails.application.config.active_record.run_after_transaction_callbacks_in_order_defined = true ### # Whether a `transaction` block is committed or rolled back when exited via `return`, `break` or `throw`. #++ # Rails.application.config.active_record.commit_transaction_on_non_local_return = true ### # Controls when to generate a value for <tt>has_secure_token</tt> declarations. #++ Rails.application.config.active_record.generate_secure_token_on = :initialize # Note: Don't need to uncomment this as it's set in application.rb ### # ** Please read carefully, this must be configured in config/application.rb ** # # Change the format of the cache entry. # # Changing this default means that all new cache entries added to the cache # will have a different format that is not supported by Rails 7.0 # applications. # # Only change this value after your application is fully deployed to Rails 7.1 # and you have no plans to rollback. # When you're ready to change format, add this to `config/application.rb` (NOT # this file): # config.active_support.cache_format_version = 7.1 ### # Configure Action View to use HTML5 standards-compliant sanitizers when they are supported on your # platform. # # `Rails::HTML::Sanitizer.best_supported_vendor` will cause Action View to use HTML5-compliant # sanitizers if they are supported, else fall back to HTML4 sanitizers. # # In previous versions of Rails, Action View always used `Rails::HTML4::Sanitizer` as its vendor. #++ # Rails.application.config.action_view.sanitizer_vendor = Rails::HTML::Sanitizer.best_supported_vendor ### # Configure Action Text to use an HTML5 standards-compliant sanitizer when it is supported on your # platform. # # `Rails::HTML::Sanitizer.best_supported_vendor` will cause Action Text to use HTML5-compliant # sanitizers if they are supported, else fall back to HTML4 sanitizers. # # In previous versions of Rails, Action Text always used `Rails::HTML4::Sanitizer` as its vendor. #++ Rails.application.config.action_text.sanitizer_vendor = Rails::HTML::Sanitizer.best_supported_vendor ### # Configure the log level used by the DebugExceptions middleware when logging # uncaught exceptions during requests. #++ Rails.application.config.action_dispatch.debug_exception_log_level = :error ### # Configure the test helpers in Action View, Action Dispatch, and rails-dom-testing to use HTML5 # parsers. # # Nokogiri::HTML5 isn't supported on JRuby, so JRuby applications must set this to :html4. # # In previous versions of Rails, these test helpers always used an HTML4 parser. #++ Rails.application.config.dom_testing_default_html_version = :html5
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/initializers/cors.rb
config/initializers/cors.rb
# frozen_string_literal: true # Allow requests from all origins to API domain Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins "*" resource "*", headers: :any, methods: [:get, :post, :put, :delete], if: proc { |env| VALID_API_REQUEST_HOSTS.include?(env["HTTP_HOST"]) } end allow do origins VALID_CORS_ORIGINS resource "/users/session_info", headers: :any, methods: [:get] end if Rails.env.development? || Rails.env.test? allow do origins "*" resource "/assets/ABCFavorit-Regular*" end end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/routes/admin.rb
config/routes/admin.rb
# frozen_string_literal: true concern :commentable do resources :comments, only: [:index, :create] end namespace :admin do get "/", to: "base#index" get :impersonate, to: "base#impersonate" delete :unimpersonate, to: "base#unimpersonate" get :redirect_to_stripe_dashboard, to: "base#redirect_to_stripe_dashboard", as: :redirect_to_stripe_dashboard get "helper_actions/impersonate/:user_id", to: "helper_actions#impersonate", as: :impersonate_helper_action get "helper_actions/stripe_dashboard/:user_id", to: "helper_actions#stripe_dashboard", as: :stripe_dashboard_helper_action get "action_call_dashboard", to: "action_call_dashboard#index" resources :users, only: [:show, :destroy], defaults: { format: "html" } do scope module: :users do concerns :commentable resource :impersonator, only: [:create, :destroy] resources :payouts, only: [:index] do collection do post :pause post :resume end end resources :email_changes, only: :index resources :merchant_accounts, only: :index resource :payout_info, only: :show resources :latest_posts, only: :index resources :stats, only: :index resources :products, only: :index, param: :external_id do scope module: :products do resources :tos_violation_flags, only: [:index, :create] resources :purchases, only: :index end end resources :guids, only: [:index] end member do post :add_credit post :mass_transfer_purchases post :probation_with_reminder post :refund_balance post :verify post :enable post :create_stripe_managed_account post :update_email post :reset_password post :confirm_email post :invalidate_active_sessions post :disable_paypal_sales post :mark_compliant post :mark_compliant_from_iffy post :suspend_for_fraud post :suspend_for_fraud_from_iffy post :flag_for_explicit_nsfw_tos_violation_from_iffy post :suspend_for_tos_violation post :put_on_probation post :flag_for_fraud post :set_custom_fee post :toggle_adult_products end end resources :affiliates, only: [] do resources :products, only: [:index], param: :external_id, module: :affiliates do resources :purchases, only: :index, module: :products end end resource :block_email_domains, only: [:show, :update] resource :unblock_email_domains, only: [:show, :update] resource :suspend_users, only: [:show, :update] resource :refund_queue, only: [:show] resources :unreviewed_users, only: [:index] resources :affiliates, only: [:index, :show], defaults: { format: "html" } get "links/:id", to: redirect("/admin/products/%{id}"), as: :link resources :products, controller: "links", only: [:show, :destroy], param: :external_id do member do post :restore post :publish delete :unpublish post :is_adult get "/file/:product_file_id/access", to: "links#access_product_file", as: :admin_access_product_file get :legacy_purchases get :views_count get :sales_stats get :access_product_file post :flag_seller_for_tos_violation get :generate_url_redirect get :join_discord get :join_discord_redirect end scope module: :products do concerns :commentable resource :details, controller: "details", only: [:show] resource :info, only: [:show] resource :staff_picked, controller: "staff_picked", only: [:create] resources :purchases, only: [:index] do collection do post :mass_refund_for_fraud end end end end resources :comments, only: :create resources :purchases, only: [:show], param: :external_id do scope module: :purchases do concerns :commentable end member do post :refund post :refund_for_fraud post :refund_taxes_only post :cancel_subscription post "change_risk_state/:state", to: "purchases#change_risk_state", as: :change_risk_state post :resend_receipt post :sync_status_with_charge_processor post :update_giftee_email post :block_buyer post :unblock_buyer post :undelete end end resources :sales_reports, only: [:index, :create] resources :merchant_accounts, only: [:show], param: :external_id do member do get :live_attributes end end # Payouts post "/paydays/pay_user/:id", to: "paydays#pay_user", as: :pay_user resources :payouts, only: [:show] do member do post :retry post :cancel post :fail post :sync end end # Search namespace :search do resources :users, only: :index resources :purchases, only: :index end get "/search_purchases", to: "search/purchases#index", as: :legacy_search_purchases # old URL for backward compatibility # Compliance resources :guids, only: [:show] scope module: "compliance" do resources :cards, only: [] do collection do post :refund end end end constraints(lambda { |request| request.env["warden"].authenticate? && request.env["warden"].user.is_team_member? }) do mount SidekiqWebCSP.new(Sidekiq::Web) => :sidekiq, as: :sidekiq_web mount FlipperCSP.new(Flipper::UI.app(Flipper)) => :features, as: :flipper_ui end scope module: "users" do post :block_ip_address end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/environments/test.rb
config/environments/test.rb
# frozen_string_literal: true require "active_support/core_ext/integer/time" # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # While tests run files are not watched, reloading is not necessary. config.enable_reloading = true # Eager loading loads your entire application. When running a single test locally, # this is usually not necessary, and can slow down your test suite. However, it's # recommended that you enable it in continuous integration systems to ensure eager # loading is working properly before deploying your code. config.eager_load = ENV["CI"].present? # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{1.hour.to_i}" } config.cache_store = :memory_store # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = true # Render exception templates for rescuable exceptions and raise for other exceptions. config.action_dispatch.show_exceptions = :rescuable # Enable request forgery protection in test environment to match production ENV, disabled by default. config.action_controller.allow_forgery_protection = true # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.asset_host = "#{PROTOCOL}://#{ASSET_DOMAIN}" config.active_storage.service = :test config.action_mailer.perform_caching = true # config.action_mailer.delivery_method is configured in config/initializers/mailer.rb config.active_record.raise_on_assign_to_attr_readonly = true # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raises error for missing translations. config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true config.logger = Logger.new(nil) if ENV["RAILS_DISABLE_TEST_LOG"] == "true" config.log_level = (ENV["RAILS_LOG_LEVEL"] || "debug").to_sym config.active_job.queue_adapter = :test config.action_controller.raise_on_missing_callback_actions = true # Suppress mongoid queries in test config.mongoid.logger.level = Logger::INFO end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/environments/development.rb
config/environments/development.rb
# frozen_string_literal: true require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded any time # it changes. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.enable_reloading = true # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable server timing config.server_timing = true # Enable/disable caching. By default caching is disabled. # Run rails dev:cache to toggle caching. if Rails.root.join("tmp/caching-dev.txt").exist? config.action_controller.perform_caching = true config.action_controller.enable_fragment_cache_logging = true config.cache_store = :mem_cache_store, *ENV.fetch("MEMCACHE_SERVERS").split(",") config.public_file_server.headers = { "Cache-Control" => "public, max-age=#{2.days.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Enable serving of images, stylesheets, and JavaScripts from an asset server. config.asset_host = "#{PROTOCOL}://#{ASSET_DOMAIN}" # Where to store uploaded files (see config/storage.yml for options) config.active_storage.service = :development # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false config.action_mailer.perform_caching = false config.action_mailer.preview_paths << "#{Rails.root}/lib/mailer_previews" # Enable serving of images, stylesheets, and JavaScripts from an asset server. config.action_mailer.asset_host = "#{PROTOCOL}://#{DOMAIN}" # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise exceptions for disallowed deprecations. config.active_support.disallowed_deprecation = :raise # Tell Active Support which deprecation messages to disallow. config.active_support.disallowed_deprecation_warnings = [] # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Highlight code that triggered database queries in logs. config.active_record.verbose_query_logs = ENV["DISABLE_VERBOSE_QUERY_LOGS"] != "1" # Highlight code that enqueued background job in logs. config.active_job.verbose_enqueue_logs = true # Suppress logger output for asset requests. config.assets.quiet = true # Raises error for missing translations. config.i18n.raise_on_missing_translations = true # Annotate rendered view with file names. # config.action_view.annotate_rendered_view_with_filenames = true # Uncomment if you wish to allow Action Cable access from any origin. # config.action_cable.disable_request_forgery_protection = true config.action_controller.raise_on_missing_callback_actions = true # Debug mongoid queries in development config.mongoid.logger.level = Logger::DEBUG # Bullet configuration for N+1 query detection config.after_initialize do Bullet.enable = true Bullet.alert = false Bullet.bullet_logger = true Bullet.rails_logger = true Bullet.add_footer = true end end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/environments/staging.rb
config/environments/staging.rb
# frozen_string_literal: true require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. config.public_file_server.enabled = false # Compress JavaScripts and CSS. config.assets.js_compressor = :terser config.assets.css_compressor = :sass # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. config.asset_host = "#{PROTOCOL}://#{ASSET_DOMAIN}" # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :amazon # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = "wss://example.com/cable" config.action_cable.allowed_request_origins = ["#{PROTOCOL}://#{DOMAIN}"] # Assume all access to the app is happening through a SSL-terminating reverse proxy. # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. # config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Log to STDOUT by default config.logger = ActiveSupport::Logger.new(STDOUT) .tap { |logger| logger.formatter = ::Logger::Formatter.new } .then { |logger| ActiveSupport::TaggedLogging.new(logger) } # Prepend all log lines with the following tags. config.log_tags = [:request_id] # "info" includes generic and useful information about system operation, but avoids logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). If you # want to log everything, set the level to "debug". config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "debug") # Use a different cache store in production. cache_namespace = (ENV["BRANCH_DEPLOYMENT"] && "#{ENV.fetch("BRANCH")}-#{ENV.fetch("REVISION")}") || ENV.fetch("REVISION") config.cache_store = :mem_cache_store, *ENV.fetch("MEMCACHE_SERVERS").split(","), { namespace: cache_namespace } # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "gumroad_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. config.action_mailer.raise_delivery_errors = true # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = [I18n.default_locale] # Send deprecation notices to registered listeners. config.active_support.report_deprecations = true # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } # Suppress mongoid queries in staging config.mongoid.logger.level = Logger::INFO end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
antiwork/gumroad
https://github.com/antiwork/gumroad/blob/638f6c3a40b23b907c09f6881d4df18339da069c/config/environments/production.rb
config/environments/production.rb
# frozen_string_literal: true require "active_support/core_ext/integer/time" Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.enable_reloading = false # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Ensures that a master key has been made available in ENV["RAILS_MASTER_KEY"], config/master.key, or an environment # key such as config/credentials/production.key. This key is used to decrypt credentials (and other encrypted files). # config.require_master_key = true # Disable serving static files from `public/`, relying on NGINX/Apache to do so instead. config.public_file_server.enabled = false # Compress JavaScripts and CSS. config.assets.js_compressor = :terser config.assets.css_compressor = :sass # Do not fall back to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Enable serving of images, stylesheets, and JavaScripts from an asset server. config.asset_host = "#{PROTOCOL}://#{ASSET_DOMAIN}" # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = "X-Sendfile" # for Apache # config.action_dispatch.x_sendfile_header = "X-Accel-Redirect" # for NGINX # Store uploaded files on the local file system (see config/storage.yml for options). config.active_storage.service = :amazon # Mount Action Cable outside main process or domain. # config.action_cable.mount_path = nil # config.action_cable.url = "wss://example.com/cable" config.action_cable.allowed_request_origins = ["#{PROTOCOL}://#{DOMAIN}"] # Assume all access to the app is happening through a SSL-terminating reverse proxy. # Can be used together with config.force_ssl for Strict-Transport-Security and secure cookies. # config.assume_ssl = true # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Log to STDOUT by default config.logger = ActiveSupport::Logger.new(STDOUT) .tap { |logger| logger.formatter = ::Logger::Formatter.new } .then { |logger| ActiveSupport::TaggedLogging.new(logger) } # Prepend all log lines with the following tags. config.log_tags = [:request_id] # "info" includes generic and useful information about system operation, but avoids logging too much # information to avoid inadvertent exposure of personally identifiable information (PII). If you # want to log everything, set the level to "debug". config.log_level = ENV.fetch("RAILS_LOG_LEVEL", "info") # Use a different cache store in production. config.cache_store = :mem_cache_store, *ENV.fetch("MEMCACHE_SERVERS").split(","), { namespace: ENV.fetch("REVISION") } # Use a real queuing backend for Active Job (and separate queues per environment). # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "gumroad_production" config.action_mailer.perform_caching = false # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = [I18n.default_locale] # Send deprecation notices to registered listeners. config.active_support.report_deprecations = true # Log disallowed deprecations. config.active_support.disallowed_deprecation = :log # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false # Enable DNS rebinding protection and other `Host` header attacks. # config.hosts = [ # "example.com", # Allow requests from example.com # /.*\.example\.com/ # Allow requests from subdomains like `www.example.com` # ] # Skip DNS rebinding protection for the default health check endpoint. # config.host_authorization = { exclude: ->(request) { request.path == "/up" } } # Suppress mongoid queries in production config.mongoid.logger.level = Logger::INFO end
ruby
MIT
638f6c3a40b23b907c09f6881d4df18339da069c
2026-01-04T15:39:11.815677Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/benchmarks/result.rb
benchmarks/result.rb
# frozen_string_literal: true require "benchmark/ips" require "coverage" Coverage.start # such meta, many wow require_relative "../lib/simplecov" require_relative "../test_projects/faked_project/lib/faked_project" result = Coverage.result class MyFormatter def format(result) result.files.map do |file| "#{file.filename}: #{file.covered_percent} #{file.lines_of_code}" end result.covered_percent.to_s end end SimpleCov.command_name "Benchmarking" SimpleCov.formatter = MyFormatter Benchmark.ips do |bm| bm.report "generating a simplecov result" do SimpleCov::Result.new(result).format! end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/support/env.rb
features/support/env.rb
# frozen_string_literal: true # While you're here, handy tip for debugging: try to attach @announce-output # @announce-command to the scenarios/features to see what's going on require "bundler" Bundler.setup require "capybara/cucumber" require "capybara/apparition" require "aruba/cucumber" require "aruba/config/jruby" if RUBY_ENGINE == "jruby" require "simplecov" # Monkey-patching Capybara::DSL if Capybara::DSLRSpecProxyInstaller has no `extended` hook unless Module.new.extend(RSpec::Matchers).extend(Capybara::DSL).singleton_class.ancestors.include?(Capybara::RSpecMatcherProxies) Capybara::DSL.extend(Module.new do def extended(base) base.extend(Capybara::RSpecMatcherProxies) if defined?(RSpec::Matchers) && base.is_a?(RSpec::Matchers) super end end) end # Rack app for Capybara which returns the latest coverage report from Aruba temp project dir coverage_dir = File.expand_path("../../tmp/aruba/project/coverage/", __dir__) Capybara.app = Rack::Builder.new do use Rack::Static, urls: {"/" => "index.html"}, root: coverage_dir run Rack::Directory.new(coverage_dir) end.to_app Capybara.configure do |config| config.ignore_hidden_elements = false config.server = :webrick config.default_driver = :apparition end Before("@branch_coverage") do skip_this_scenario unless SimpleCov.branch_coverage_supported? end Before("@rails6") do # Rails 6 only supports Ruby 2.5+ skip_this_scenario if Gem::Version.new(RUBY_VERSION) < Gem::Version.new("2.5") end Before("@process_fork") do # Process.fork is NotImplementedError in jruby skip_this_scenario if jruby? end Before("@no_jruby") do skip_this_scenario if jruby? end def jruby? defined?(RUBY_ENGINE) && RUBY_ENGINE == "jruby" end Aruba.configure do |config| config.allow_absolute_paths = true # JRuby needs a bit longer to get going config.exit_timeout = RUBY_ENGINE == "jruby" ? 60 : 20 end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/parameter_types.rb
features/step_definitions/parameter_types.rb
# frozen_string_literal: true # # Enforce the alphabetical execution of specs because rspec 2+ executes them # randomly with `rspec spec` while we need them in an accurate order for coverage # reports that include the spec files. # # This is due to the fact that coverage will not include the first loaded spec/test file. # To get predictable coverage results, we need to know which one that is... ParameterType( name: "rspec", regexp: /bundle exec rspec spec/, transformer: lambda { |_| files = nil # Avoid shadowing cd(".") { files = Dir["spec/**/*_spec.rb"] } "bundle exec rspec #{files.sort.join(' ')}" } )
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/simplecov_steps.rb
features/step_definitions/simplecov_steps.rb
# frozen_string_literal: true # Just a shortcut to make framework setup more readable # The test project is using separate config files to avoid specifying all of # test/spec_helper in the features every time. Given /^SimpleCov for (.*) is configured with:$/ do |framework, config_body| framework_dir = case framework when /RSpec/i "spec" when /Test\/Unit/i "test" when /Cucumber/i "features/support" when /Minitest/i "minitest" else raise ArgumentError, "Could not identify test framework #{framework}!" end steps %( Given a file named "#{framework_dir}/simplecov_config.rb" with: """ #{config_body} """ ) end When /^I open the coverage report generated with `([^`]+)`$/ do |command| steps %( When I successfully run `#{command}` Then a coverage report should have been generated When I open the coverage report ) end Then /^a coverage report should have been generated(?: in "([^"]*)")?$/ do |coverage_dir| coverage_dir ||= "coverage" steps %( Then the output should contain "Coverage report generated" And a directory named "#{coverage_dir}" should exist And the following files should exist: | #{coverage_dir}/index.html | | #{coverage_dir}/.resultset.json | ) end Then /^a JSON coverage report should have been generated(?: in "([^"]*)")?$/ do |coverage_dir| coverage_dir ||= "coverage" steps %( Then the output should contain "Coverage report generated" And a directory named "#{coverage_dir}" should exist And the following files should exist: | #{coverage_dir}/coverage.json | ) end Then /^no coverage report should have been generated(?: in "([^"]*)")?$/ do |coverage_dir| coverage_dir ||= "coverage" steps %( Then the output should not contain "Coverage report generated" And a directory named "#{coverage_dir}" should not exist And the following files should not exist: | #{coverage_dir}/index.html | | #{coverage_dir}/.resultset.json | ) end Then /^the report should be based upon:$/ do |table| frameworks = table.raw.flatten steps %( Then the output should contain "Coverage report generated for #{frameworks.join(', ')}" And I should see "using #{frameworks.join(', ')}" within "#footer" ) end # This is necessary to ensure timing-dependant tests like the merge timeout # do not fail on powerful machines. When /^I wait for (\d+) seconds$/ do |seconds| sleep seconds.to_i end Then "the overlay should be open" do expect(page).to have_css("#cboxContent") end When "I install dependencies" do # bundle may take its time steps %( When I successfully run `bundle` for up to 120 seconds ) end When "I pry" do require "pry" # rubocop:disable Lint/Debugger binding.pry # rubocop:enable Lint/Debugger end Given "I'm working on the project {string}" do |project_name| this_dir = File.dirname(__FILE__) # Clean up and create blank state for project cd(".") do FileUtils.rm_rf "project" FileUtils.cp_r File.join(this_dir, "../../test_projects/#{project_name}/"), "project" end step 'I cd to "project"' end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/web_steps.rb
features/step_definitions/web_steps.rb
# frozen_string_literal: true module WithinHelpers def with_scope(locator) locator ? within(locator) { yield } : yield end end World(WithinHelpers) When /^I open the coverage report$/ do visit "/" end Given /^(?:|I )am on (.+)$/ do |path| visit path end When /^(?:|I )go to (.+)$/ do |path| visit path end When /^(?:|I )press "([^"]*)"(?: within "([^"]*)")?$/ do |button, selector| with_scope(selector) do click_button(button) end end When /^(?:|I )follow "([^"]*)"(?: within "([^"]*)")?$/ do |link, selector| with_scope(selector) do click_link(link) end end Then /^(?:|I )should see "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| with_scope(selector) do expect(page).to have_content(text) end end Then /^(?:|I )should see \/([^\/]*)\/(?: within "([^"]*)")?$/ do |regexp, selector| regexp = Regexp.new(regexp) with_scope(selector) do expect(page).to have_xpath("//*", text: regexp) end end Then /^(?:|I )should not see "([^"]*)"(?: within "([^"]*)")?$/ do |text, selector| with_scope(selector) do expect(page).not_to have_content(text) end end Then /^(?:|I )should not see \/([^\/]*)\/(?: within "([^"]*)")?$/ do |regexp, selector| regexp = Regexp.new(regexp) with_scope(selector) do expect(page).not_to have_xpath("//*", text: regexp) end end # the default in our settings is still to check unvisible content # as well and until we change that these steps similar to "should (not) # see" are necessary Then "{string} should be visible" do |text| expect(page).to have_content(:visible, text) end Then "{string} should not be visible" do |text| expect(page).not_to have_content(:visible, text) end Then /^show me the page$/ do save_and_open_page # rubocop:disable Lint/Debugger end Then /^print the page$/ do puts page.body end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/json_steps.rb
features/step_definitions/json_steps.rb
# frozen_string_literal: true Then /^the JSON coverage report should match the output for the basic case$/ do cd(".") do json_report = JSON.parse(File.read("coverage/coverage.json")) coverage_hash = json_report.fetch "coverage" directory = Dir.pwd expect(coverage_hash.fetch("#{directory}/lib/faked_project.rb")).to eq "lines" => [nil, nil, 1, 1, 1, nil, nil, nil, 5, 3, nil, nil, 1] expect(coverage_hash.fetch("#{directory}/lib/faked_project/some_class.rb")).to eq "lines" => [nil, nil, 1, 1, 1, nil, 1, 2, nil, nil, 1, 1, nil, nil, 1, 1, 1, nil, 0, nil, nil, 0, nil, nil, 1, nil, 1, 0, nil, nil] end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/old_coverage_json_steps.rb
features/step_definitions/old_coverage_json_steps.rb
# frozen_string_literal: true RESULTSET_JSON_PATH = "coverage/.resultset.json" PATH_PLACE_HOLDER = "$$path" COMMAND_NAME = "RSpec Different Name to avoid overriding" Given "the paths in the old .resultset.json are adjusted to the current environment" do in_current_directory do resultset_json_content = File.read(RESULTSET_JSON_PATH) File.write(RESULTSET_JSON_PATH, resultset_json_content.gsub(PATH_PLACE_HOLDER, Dir.pwd)) end end Given "the timestamp in the .resultset.json is current" do in_current_directory do resultset_json = File.read(RESULTSET_JSON_PATH) resultset_hash = JSON.parse(resultset_json) resultset_hash[COMMAND_NAME]["timestamp"] = Time.now.to_i File.write(RESULTSET_JSON_PATH, JSON.pretty_generate(resultset_hash)) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/html_steps.rb
features/step_definitions/html_steps.rb
# frozen_string_literal: true Then /^I should see the groups:$/ do |table| expected_groups = table.hashes # Given group names should be the same number than those rendered in report expect(page).to have_css("#content .file_list_container", count: expected_groups.count) # Verify each of the expected groups has a file list container and corresponding title and coverage number # as well as the correct number of links to files. expected_groups.each do |group| with_scope "#content ##{group['name'].gsub(/[^a-z]/i, '')}.file_list_container" do file_count_in_group = page.all("a.src_link").count expect(file_count_in_group).to eq(group["files"].to_i) with_scope "h2" do expect(page).to have_content(group["name"]) expect(page).to have_content(group["coverage"]) end end end end Then /^I should see the source files:$/ do |table| expected_files = table.hashes available_source_files = all(".t-file", visible: true, count: expected_files.count) include_branch_coverage = table.column_names.include?("branch coverage") # Find all filenames and their coverage present in coverage report files = available_source_files.map do |file_row| coverage_data = { "name" => file_row.find(".t-file__name").text, "coverage" => file_row.find(".t-file__coverage").text } coverage_data["branch coverage"] = file_row.find(".t-file__branch-coverage").text if include_branch_coverage coverage_data end expect(files.sort_by { |coverage_data| coverage_data["name"] }).to eq(expected_files.sort_by { |coverage_data| coverage_data["name"] }) end Then /^there should be (\d+) skipped lines in the source files$/ do |expected_count| expect(all(".source_table ol li.skipped").count).to eq(expected_count.to_i) end Then /^I should see a (.+) coverage summary of (\d+)\/(\d+)( for the file)?$/ do |coverage_type, hit, total, for_file| missed = total - hit extra_class = for_file ? ".source_table" : "" summary_text = find("#{extra_class} .t-#{coverage_type}-summary", visible: true).text expect(summary_text).to match /#{total} .+ #{hit} .+ #{missed} / end When /^I open the detailed view for "(.+)"$/ do |file_path| click_link(file_path, class: "src_link", title: file_path) expect(page).to have_css(".header h3", visible: true, text: file_path) end When "I close the detailed view" do click_button "cboxClose" end Then /^I should see coverage branch data like "(.+)"$/ do |text| expect(find(".hits", visible: true, text: text)).to be_truthy end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/features/step_definitions/parallel_tests_steps.rb
features/step_definitions/parallel_tests_steps.rb
# frozen_string_literal: true Then "I should see the line coverage results for the parallel tests project" do steps %( Then I should see the groups: | name | coverage | files | | All Files | 89.36% | 9 | And I should see the source files: | name | coverage | | lib/all.rb | 100.00 % | | spec/a_spec.rb | 100.00 % | | spec/b_spec.rb | 100.00 % | | spec/c_spec.rb | 100.00 % | | spec/d_spec.rb | 100.00 % | | lib/a.rb | 85.71 % | | lib/b.rb | 80.00 % | | lib/c.rb | 75.00 % | | lib/d.rb | 71.43 % | ) end Then "I should see the branch coverage results for the parallel tests project" do steps %( Then I should see the groups: | name | coverage | files | | All Files | 89.36% | 9 | And I should see a line coverage summary of 42/47 And I should see a branch coverage summary of 4/8 And I should see the source files: | name | coverage | branch coverage | | lib/all.rb | 100.00 % | 100.00 % | | spec/a_spec.rb | 100.00 % | 100.00 % | | spec/b_spec.rb | 100.00 % | 100.00 % | | spec/c_spec.rb | 100.00 % | 100.00 % | | spec/d_spec.rb | 100.00 % | 100.00 % | | lib/a.rb | 85.71 % | 50.00 % | | lib/b.rb | 80.00 % | 100.00 % | | lib/c.rb | 75.00 % | 50.00 % | | lib/d.rb | 71.43 % | 50.00 % | ) end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/filters_spec.rb
spec/filters_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::SourceFile do subject do SimpleCov::SourceFile.new(source_fixture("sample.rb"), [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]) end it "doesn't match a new SimpleCov::StringFilter 'foobar'" do expect(SimpleCov::StringFilter.new("foobar")).not_to be_matches subject end it "doesn't match a new SimpleCov::StringFilter 'some/path'" do expect(SimpleCov::StringFilter.new("some/path")).not_to be_matches subject end it "matches a new SimpleCov::StringFilter 'spec/fixtures'" do expect(SimpleCov::StringFilter.new("spec/fixtures")).to be_matches subject end it "matches a new SimpleCov::StringFilter 'spec/fixtures/sample.rb'" do expect(SimpleCov::StringFilter.new("spec/fixtures/sample.rb")).to be_matches subject end it "matches a new SimpleCov::StringFilter 'sample.rb'" do expect(SimpleCov::StringFilter.new("sample.rb")).to be_matches subject end it "doesn't match a new SimpleCov::StringFilter '.pl'" do expect(SimpleCov::StringFilter.new(".pl")).not_to be_matches subject end it "doesn't match a parent directory with a new SimpleCov::StringFilter" do parent_dir_name = File.basename(File.expand_path("..", File.dirname(__FILE__))) expect(SimpleCov::StringFilter.new(parent_dir_name)).not_to be_matches subject end it "matches a new SimpleCov::RegexFilter //fixtures//" do expect(SimpleCov::RegexFilter.new(/\/fixtures\//)).to be_matches subject end it "doesn't match a new SimpleCov::RegexFilter /^/fixtures//" do expect(SimpleCov::RegexFilter.new(/^\/fixtures\//)).not_to be_matches subject end it "matches a new SimpleCov::RegexFilter /^/spec//" do expect(SimpleCov::RegexFilter.new(/^\/spec\//)).to be_matches subject end it "doesn't match a new SimpleCov::BlockFilter that is not applicable" do expect(SimpleCov::BlockFilter.new(proc { |s| File.basename(s.filename) == "foo.rb" })).not_to be_matches subject end it "matches a new SimpleCov::BlockFilter that is applicable" do expect(SimpleCov::BlockFilter.new(proc { |s| File.basename(s.filename) == "sample.rb" })).to be_matches subject end it "matches a new SimpleCov::ArrayFilter when 'sample.rb' is passed as array" do expect(SimpleCov::ArrayFilter.new(["sample.rb"])).to be_matches subject end it "doesn't match a new SimpleCov::ArrayFilter when a file path different than 'sample.rb' is passed as array" do expect(SimpleCov::ArrayFilter.new(["other_file.rb"])).not_to be_matches subject end it "matches a new SimpleCov::ArrayFilter when two file paths including 'sample.rb' are passed as array" do expect(SimpleCov::ArrayFilter.new(["sample.rb", "other_file.rb"])).to be_matches subject end it "doesn't match a parent directory with a new SimpleCov::ArrayFilter" do parent_dir_name = File.basename(File.expand_path("..", File.dirname(__FILE__))) expect(SimpleCov::ArrayFilter.new([parent_dir_name])).not_to be_matches subject end it "matches a new SimpleCov::ArrayFilter when /sample.rb/ is passed as array" do expect(SimpleCov::ArrayFilter.new([/sample.rb/])).to be_matches subject end it "doesn't match a new SimpleCov::ArrayFilter when a file path different than /sample.rb/ is passed as array" do expect(SimpleCov::ArrayFilter.new([/other_file.rb/])).not_to be_matches subject end it "matches a new SimpleCov::ArrayFilter when a block is passed as array and returns true" do expect(SimpleCov::ArrayFilter.new([proc { true }])).to be_matches subject end it "doesn't match a new SimpleCov::ArrayFilter when a block that returns false is passed as array" do expect(SimpleCov::ArrayFilter.new([proc { false }])).not_to be_matches subject end it "matches a new SimpleCov::ArrayFilter when a custom class that returns true is passed as array" do filter = Class.new(SimpleCov::Filter) do def matches?(_source_file) true end end.new(nil) expect(SimpleCov::ArrayFilter.new([filter])).to be_matches subject end it "doesn't match a new SimpleCov::ArrayFilter when a custom class that returns false is passed as array" do filter = Class.new(SimpleCov::Filter) do def matches?(_source_file) false end end.new(nil) expect(SimpleCov::ArrayFilter.new([filter])).not_to be_matches subject end context "with no filters set up and a basic source file in an array" do subject do [SimpleCov::SourceFile.new(source_fixture("sample.rb"), [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil])] end before do @prev_filters = SimpleCov.filters SimpleCov.filters = [] end after do SimpleCov.filters = @prev_filters end it 'returns 0 items after executing SimpleCov.filtered on files when using a "sample" string filter' do SimpleCov.add_filter "sample" expect(SimpleCov.filtered(subject).count).to be_zero end it 'returns 0 items after executing SimpleCov.filtered on files when using a "spec/fixtures" string filter' do SimpleCov.add_filter "spec/fixtures" expect(SimpleCov.filtered(subject).count).to be_zero end it 'returns 1 item after executing SimpleCov.filtered on files when using a "fooo" string filter' do SimpleCov.add_filter "fooo" expect(SimpleCov.filtered(subject).count).to eq(1) end it "returns 0 items after executing SimpleCov.filtered on files when using a block filter that returns true" do SimpleCov.add_filter do true end expect(SimpleCov.filtered(subject).count).to be_zero end it "returns 1 item after executing SimpleCov.filtered on files when using an always-false block filter" do SimpleCov.add_filter do false end expect(SimpleCov.filtered(subject).count).to eq(1) end it "returns a FileList after filtering" do SimpleCov.add_filter "fooo" expect(SimpleCov.filtered(subject)).to be_a SimpleCov::FileList end end context "with the default configuration" do skip "requires the default configuration" if ENV["SIMPLECOV_NO_DEFAULTS"] def a_file(path) path = File.join(SimpleCov.root, path) unless path.start_with?("/") SimpleCov::SourceFile.new(path, [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]) end context "inside the project" do it "doesn't filter" do expect(SimpleCov.filtered([a_file("foo.rb")]).count).to eq(1) end it "filters vendor/bundle" do expect(SimpleCov.filtered([a_file("vendor/bundle/foo.rb")]).count).to eq(0) end it "filters hidden folders" do expect(SimpleCov.filtered([a_file(".semaphore-cache/lib.rb")]).count).to eq(0) end it "filters hidden files" do expect(SimpleCov.filtered([a_file(".hidden_config.rb")]).count).to eq(0) end it "doesn't filter hidden files further down the path" do expect(SimpleCov.filtered([a_file("some_dir/.sneaky.rb")]).count).to eq(1) end end context "outside the project" do it "filters" do expect(SimpleCov.filtered([a_file("/other/path/foo.rb")]).count).to eq(0) end it "filters even if the sibling directory has SimpleCov.root as a prefix" do sibling_dir = "#{SimpleCov.root}_cache" expect(SimpleCov.filtered([a_file("#{sibling_dir}/foo.rb")]).count).to eq(0) end end end describe ".class_for_argument" do it "returns SimpleCov::StringFilter for a string" do expect(SimpleCov::Filter.class_for_argument("filestring")).to eq(SimpleCov::StringFilter) end it "returns SimpleCov::RegexFilter for a string" do expect(SimpleCov::Filter.class_for_argument(/regex/)).to eq(SimpleCov::RegexFilter) end it "returns SimpleCov::RegexFilter for a string" do expect(SimpleCov::Filter.class_for_argument(%w[file1 file2])).to eq(SimpleCov::ArrayFilter) end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/result_spec.rb
spec/result_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::Result do context "with a (mocked) Coverage.result" do before do @prev_filters = SimpleCov.filters SimpleCov.filters = [] @prev_groups = SimpleCov.groups SimpleCov.groups = {} @prev_formatter = SimpleCov.formatter SimpleCov.formatter = nil end after do SimpleCov.filters = @prev_filters SimpleCov.groups = @prev_groups SimpleCov.formatter = @prev_formatter end let(:original_result) do { source_fixture("sample.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil]}, source_fixture("app/models/user.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]}, source_fixture("app/controllers/sample_controller.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]} } end context "a simple cov result initialized from that" do subject { SimpleCov::Result.new(original_result) } it "has 3 filenames" do expect(subject.filenames.count).to eq(3) end it "has 3 source files" do expect(subject.source_files.count).to eq(3) subject.source_files.each do |source_file| expect(source_file).to be_a SimpleCov::SourceFile end end it "returns an instance of SimpleCov::FileList for source_files and files" do expect(subject.files).to be_a SimpleCov::FileList expect(subject.source_files).to be_a SimpleCov::FileList end it "has files equal to source_files" do expect(subject.files).to eq(subject.source_files) end it "has accurate covered percent" do # in our fixture, there are 13 covered line (result in 1) in all 15 relevant line (result in non-nil) expect(subject.covered_percent).to eq(86.66666666666667) end it "has accurate covered percentages" do expect(subject.covered_percentages).to eq([80.0, 80.0, 100.0]) end it "has accurate least covered file" do expect(subject.least_covered_file).to match(/sample_controller.rb/) end %i[covered_percent covered_percentages least_covered_file covered_strength covered_lines missed_lines total_lines].each do |msg| it "responds to #{msg}" do expect(subject).to respond_to(msg) end end context "dumped with to_hash" do it "is a hash" do expect(subject.to_hash).to be_a Hash end context "loaded back with from_hash" do let(:dumped_result) do SimpleCov::Result.from_hash(subject.to_hash).first end it "has 3 source files" do expect(dumped_result.source_files.count).to eq(subject.source_files.count) end it "has the same covered_percent" do expect(dumped_result.covered_percent).to eq(subject.covered_percent) end it "has the same covered_percentages" do expect(dumped_result.covered_percentages).to eq(subject.covered_percentages) end it "has the same timestamp" do expect(dumped_result.created_at.to_i).to eq(subject.created_at.to_i) end it "has the same command_name" do expect(dumped_result.command_name).to eq(subject.command_name) end it "has the same original_result" do expect(dumped_result.original_result).to eq(subject.original_result) end end end end context "with some filters set up" do before do SimpleCov.add_filter "sample.rb" end it "has 2 files in a new simple cov result" do expect(SimpleCov::Result.new(original_result).source_files.length).to eq(2) end it "has 80 covered percent" do expect(SimpleCov::Result.new(original_result).covered_percent).to eq(80) end it "has [80.0, 80.0] covered percentages" do expect(SimpleCov::Result.new(original_result).covered_percentages).to eq([80.0, 80.0]) end end context "with groups set up for all files" do subject do SimpleCov::Result.new(original_result) end before do SimpleCov.add_group "Models", "app/models" SimpleCov.add_group "Controllers", ["app/controllers"] SimpleCov.add_group "Other" do |src_file| File.basename(src_file.filename) == "sample.rb" end end it "has 3 groups" do expect(subject.groups.length).to eq(3) end it "has user.rb in 'Models' group" do expect(File.basename(subject.groups["Models"].first.filename)).to eq("user.rb") end it "has sample_controller.rb in 'Controllers' group" do expect(File.basename(subject.groups["Controllers"].first.filename)).to eq("sample_controller.rb") end context "and simple formatter being used" do before do SimpleCov.formatter = SimpleCov::Formatter::SimpleFormatter end it "returns a formatted string with result.format!" do expect(subject.format!).to be_a String end end context "and multi formatter being used" do before do SimpleCov.formatters = [ SimpleCov::Formatter::SimpleFormatter, SimpleCov::Formatter::SimpleFormatter ] end it "returns an array containing formatted string with result.format!" do formatted = subject.format! expect(formatted.count).to eq(2) expect(formatted.first).to be_a String end end end context "with groups set up that do not match all files" do subject { SimpleCov::Result.new(original_result) } before do SimpleCov.configure do add_group "Models", "app/models" add_group "Controllers", "app/controllers" end end it "has 3 groups" do expect(subject.groups.length).to eq(3) end it "has 1 item per group" do subject.groups.each_value do |files| expect(files.length).to eq(1) end end it 'has sample.rb in "Ungrouped" group' do expect(File.basename(subject.groups["Ungrouped"].first.filename)).to eq("sample.rb") end it "returns all groups as instances of SimpleCov::FileList" do subject.groups.each_value do |files| expect(files).to be_a SimpleCov::FileList end end end describe ".from_hash" do let(:other_result) do { source_fixture("sample.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 0, 0, nil, nil]} } end let(:created_at) { Time.now.to_i } it "can consume multiple commands" do input = { "rspec" => { "coverage" => original_result, "timestamp" => created_at }, "cucumber" => { "coverage" => other_result, "timestamp" => created_at } } result = described_class.from_hash(input) expect(result.size).to eq 2 sorted = result.sort_by(&:command_name) expect(sorted.map(&:command_name)).to eq %w[cucumber rspec] expect(sorted.map(&:created_at).map(&:to_i)).to eq [created_at, created_at] expect(sorted.map(&:original_result)).to eq [other_result, original_result] end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/multi_formatter_spec.rb
spec/multi_formatter_spec.rb
# frozen_string_literal: true require "helper" require "simplecov/formatter/multi_formatter" describe SimpleCov::Formatter::MultiFormatter do describe ".[]" do # Regression test for https://github.com/simplecov-ruby/simplecov/issues/428 it "constructs a formatter with multiple children" do # Silence deprecation warnings. allow(described_class).to receive(:warn) children = [ SimpleCov::Formatter::SimpleFormatter, SimpleCov::Formatter::SimpleFormatter ] expect(described_class[*children].new.formatters).to eq(children) end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/file_list_spec.rb
spec/file_list_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::Result do subject do original_result = { source_fixture("sample.rb") => { "lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil], "branches" => {} }, source_fixture("app/models/user.rb") => { "lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil], "branches" => {} }, source_fixture("app/controllers/sample_controller.rb") => { "lines" => [nil, 2, 2, 0, nil, nil, 0, nil, nil, nil], "branches" => {} } } SimpleCov::Result.new(original_result).files end it "has 11 covered lines" do expect(subject.covered_lines).to eq(11) end it "has 3 missed lines" do expect(subject.missed_lines).to eq(3) end it "has 17 never lines" do expect(subject.never_lines).to eq(17) end it "has 14 lines of code" do expect(subject.lines_of_code).to eq(14) end it "has 5 skipped lines" do expect(subject.skipped_lines).to eq(5) end it "has the correct covered percent" do expect(subject.covered_percent).to eq(78.57142857142857) end it "has the correct covered percentages" do expect(subject.covered_percentages).to eq([50.0, 80.0, 100.0]) end it "has the correct least covered file" do expect(subject.least_covered_file).to match(/sample_controller.rb/) end it "has the correct covered strength" do expect(subject.covered_strength).to eq(0.9285714285714286) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/coverage_for_eval_spec.rb
spec/coverage_for_eval_spec.rb
# frozen_string_literal: true require "helper" RSpec.describe "coverage for eval" do if SimpleCov.coverage_for_eval_supported? around do |test| Dir.chdir(File.join(File.dirname(__FILE__), "fixtures", "eval_test")) do FileUtils.rm_rf("./coverage") test.call end end before do @stdout, @stderr, @status = Open3.capture3(command) end context "foo" do let(:command) { "bundle e ruby eval_test.rb" } it "records coverage for erb" do expect(@stdout).to include("Line Coverage: 66.67% (2 / 3)") end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/command_guesser_spec.rb
spec/command_guesser_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::CommandGuesser do subject { SimpleCov::CommandGuesser } it 'correctly guesses "Unit Tests" for unit tests' do subject.original_run_command = "/some/path/test/units/foo_bar_test.rb" expect(subject.guess).to eq("Unit Tests") subject.original_run_command = "test/units/foo.rb" expect(subject.guess).to eq("Unit Tests") subject.original_run_command = "test/foo.rb" expect(subject.guess).to eq("Unit Tests") subject.original_run_command = "test/{models,helpers,unit}/**/*_test.rb" expect(subject.guess).to eq("Unit Tests") end it 'correctly guesses "Functional Tests" for functional tests' do subject.original_run_command = "/some/path/test/functional/foo_bar_controller_test.rb" expect(subject.guess).to eq("Functional Tests") subject.original_run_command = "test/{controllers,mailers,functional}/**/*_test.rb" expect(subject.guess).to eq("Functional Tests") end it 'correctly guesses "Integration Tests" for integration tests' do subject.original_run_command = "/some/path/test/integration/foo_bar_controller_test.rb" expect(subject.guess).to eq("Integration Tests") subject.original_run_command = "test/integration/**/*_test.rb" expect(subject.guess).to eq("Integration Tests") end it 'correctly guesses "Cucumber Features" for cucumber features' do subject.original_run_command = "features" expect(subject.guess).to eq("Cucumber Features") subject.original_run_command = "cucumber" expect(subject.guess).to eq("Cucumber Features") end it 'correctly guesses "RSpec" for RSpec' do subject.original_run_command = "/some/path/spec/foo.rb" expect(subject.guess).to eq("RSpec") end it "defaults to RSpec because RSpec constant is defined" do subject.original_run_command = "some_arbitrary_command with arguments" expect(subject.guess).to eq("RSpec") end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/coverage_statistics_spec.rb
spec/coverage_statistics_spec.rb
# frozen_string_literal: true require "helper" RSpec.describe SimpleCov::CoverageStatistics do describe ".new" do it "retains statistics and computes new ones" do statistics = described_class.new(covered: 4, missed: 6, total_strength: 14) expect(statistics.covered).to eq 4 expect(statistics.missed).to eq 6 expect(statistics.total).to eq 10 expect(statistics.percent).to eq 40.0 expect(statistics.strength).to eq 1.4 end it "can omit the total strength defaulting to 0.0" do statistics = described_class.new(covered: 4, missed: 6) expect(statistics.strength).to eq 0.0 end it "can deal with it if everything is 0" do statistics = described_class.new(covered: 0, missed: 0, total_strength: 0.0) expect_all_empty(statistics) end end describe ".from" do it "returns an all 0s coverage statistics if there are no statistics" do statistics = described_class.from([]) expect_all_empty(statistics) end it "returns all empty statistics when initialized with a couple of empty results" do statistics = described_class.from([empty_statistics, empty_statistics]) expect_all_empty(statistics) end it "produces sensible total results" do statistics = described_class.from( [ described_class.new(covered: 3, missed: 4, total_strength: 54), described_class.new(covered: 0, missed: 13, total_strength: 0), described_class.new(covered: 37, missed: 0, total_strength: 682) ] ) expect(statistics.covered).to eq 40 expect(statistics.missed).to eq 17 expect(statistics.total).to eq 57 expect(statistics.percent).to be_within(0.01).of(70.18) expect(statistics.strength).to be_within(0.01).of(12.91) end end def empty_statistics described_class.new(covered: 0, missed: 0, total_strength: 0.0) end def expect_all_empty(statistics) expect(statistics.covered).to eq 0 expect(statistics.missed).to eq 0 expect(statistics.total).to eq 0 # might be counter-intuitive but think of it as "we covered everything we could" expect(statistics.percent).to eq 100.0 expect(statistics.strength).to eq 0.0 end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/configuration_spec.rb
spec/configuration_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::Configuration do let(:config_class) do Class.new do include SimpleCov::Configuration end end let(:config) { config_class.new } describe "#print_error_status" do subject { config.print_error_status } context "when not manually set" do it { is_expected.to be true } end context "when manually set" do before { config.print_error_status = false } it { is_expected.to be false } end end describe "#tracked_files" do context "when configured" do let(:glob) { "{app,lib}/**/*.rb" } before { config.track_files(glob) } it "returns the configured glob" do expect(config.tracked_files).to eq glob end context "and configured again with nil" do before { config.track_files(nil) } it "returns nil" do expect(config.tracked_files).to be_nil end end end context "when unconfigured" do it "returns nil" do expect(config.tracked_files).to be_nil end end shared_examples "setting coverage expectations" do |coverage_setting| after do config.clear_coverage_criteria end it "does not warn you about your usage" do expect(config).not_to receive(:warn) config.public_send(coverage_setting, 100.00) end it "warns you about your usage" do expect(config).to receive(:warn).with("The coverage you set for #{coverage_setting} is greater than 100%") config.public_send(coverage_setting, 100.01) end it "sets the right coverage value when called with a number" do config.public_send(coverage_setting, 80) expect(config.public_send(coverage_setting)).to eq line: 80 end it "sets the right coverage when called with a hash of just line" do config.public_send(coverage_setting, {line: 85.0}) expect(config.public_send(coverage_setting)).to eq line: 85.0 end it "sets the right coverage when called with a hash of just branch" do config.enable_coverage :branch config.public_send(coverage_setting, {branch: 85.0}) expect(config.public_send(coverage_setting)).to eq branch: 85.0 end it "sets the right coverage when called with both line and branch" do config.enable_coverage :branch config.public_send(coverage_setting, {branch: 85.0, line: 95.4}) expect(config.public_send(coverage_setting)).to eq branch: 85.0, line: 95.4 end it "raises when trying to set branch coverage but not enabled" do expect do config.public_send(coverage_setting, {branch: 42}) end.to raise_error(/branch.*disabled/i) end it "raises when unknown coverage criteria provided" do expect do config.public_send(coverage_setting, {unknown: 42}) end.to raise_error(/unsupported.*unknown/i) end context "when primary coverage is set" do before do config.enable_coverage :branch config.primary_coverage :branch end it "sets the right coverage value when called with a number" do config.public_send(coverage_setting, 80) expect(config.public_send(coverage_setting)).to eq branch: 80 end end end describe "#minimum_coverage" do it_behaves_like "setting coverage expectations", :minimum_coverage end describe "#minimum_coverage_by_file" do it_behaves_like "setting coverage expectations", :minimum_coverage_by_file end describe "#maximum_coverage_drop" do it_behaves_like "setting coverage expectations", :maximum_coverage_drop end describe "#refuse_coverage_drop" do after do config.clear_coverage_criteria end it "sets the right coverage value when called with `:line`" do config.refuse_coverage_drop(:line) expect(config.maximum_coverage_drop).to eq line: 0 end it "sets the right coverage value when called with `:branch`" do config.enable_coverage :branch config.refuse_coverage_drop(:branch) expect(config.maximum_coverage_drop).to eq branch: 0 end it "sets the right coverage value when called with `:line` and `:branch`" do config.enable_coverage :branch config.refuse_coverage_drop(:line, :branch) expect(config.maximum_coverage_drop).to eq line: 0, branch: 0 end it "sets the right coverage value when called with no args" do config.refuse_coverage_drop expect(config.maximum_coverage_drop).to eq line: 0 end end describe "#coverage_criterion" do it "defaults to line" do expect(config.coverage_criterion).to eq :line end it "works fine with line" do config.coverage_criterion :line expect(config.coverage_criterion).to eq :line end it "works fine with :branch" do config.coverage_criterion :branch expect(config.coverage_criterion).to eq :branch end it "works fine setting it back and forth" do config.coverage_criterion :branch config.coverage_criterion :line expect(config.coverage_criterion).to eq :line end it "errors out on unknown coverage" do expect do config.coverage_criterion :unknown end.to raise_error(/unsupported.*unknown.*line/i) end end describe "#coverage_criteria" do it "defaults to line" do expect(config.coverage_criteria).to contain_exactly :line end end describe "#enable_coverage" do it "can enable branch coverage" do config.enable_coverage :branch expect(config.coverage_criteria).to contain_exactly :line, :branch end it "can enable line again" do config.enable_coverage :line expect(config.coverage_criteria).to contain_exactly :line end it "can't enable arbitrary things" do expect do config.enable_coverage :unknown end.to raise_error(/unsupported.*unknown.*line/i) end end describe "#branch_coverage?", if: SimpleCov.branch_coverage_supported? do it "returns true of branch coverage is being measured" do config.enable_coverage :branch expect(config).to be_branch_coverage end it "returns false for line coverage" do config.coverage_criterion :line expect(config).not_to be_branch_coverage end end describe "#enable_for_subprocesses" do it "returns false by default" do expect(config.enable_for_subprocesses).to eq false end it "can be set to true" do config.enable_for_subprocesses true expect(config.enable_for_subprocesses).to eq true end it "can be enabled and then disabled again" do config.enable_for_subprocesses true config.enable_for_subprocesses false expect(config.enable_for_subprocesses).to eq false end end describe "#primary_coverage" do context "when branch coverage is enabled" do before { config.enable_coverage :branch } it "can set primary coverage to branch" do config.primary_coverage :branch expect(config.coverage_criteria).to contain_exactly :line, :branch expect(config.primary_coverage).to eq :branch end end context "when branch coverage is not enabled" do it "cannot set primary coverage to branch" do expect do config.primary_coverage :branch end.to raise_error(/branch.*disabled/i) end end it "can set primary coverage to line" do config.primary_coverage :line expect(config.coverage_criteria).to contain_exactly :line expect(config.primary_coverage).to eq :line end it "can't set primary coverage to arbitrary things" do expect do config.primary_coverage :unknown end.to raise_error(/unsupported.*unknown.*line/i) end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/default_formatter_spec.rb
spec/default_formatter_spec.rb
# frozen_string_literal: true require "helper" require "simplecov_json_formatter" describe SimpleCov::Formatter do describe ".from_env" do let(:env) { {"CC_TEST_REPORTER_ID" => "4c9f1de6193f30799e9a5d5c082692abecc1fd2c6aa62c621af7b2a910761970"} } context "when CC_TEST_REPORTER_ID environment variable is set" do it "returns an array containing the HTML and JSON formatters" do expect(described_class.from_env(env)).to eq([ SimpleCov::Formatter::HTMLFormatter, SimpleCov::Formatter::JSONFormatter ]) end end context "when CC_TEST_REPORTER_ID environment variable isn't set" do let(:env) { {} } it "returns an array containing only the HTML formatter" do expect(described_class.from_env(env)).to eq([ SimpleCov::Formatter::HTMLFormatter ]) end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/gemspec_spec.rb
spec/gemspec_spec.rb
# frozen_string_literal: true require "open3" RSpec.describe "gemspec sanity" do after do File.delete(Dir.glob("simplecov-*.gem").first) end let(:build) do Bundler.with_original_env do Open3.capture3("gem build simplecov.gemspec") end end it "has no warnings" do expect(build[1]).not_to include("WARNING") end it "succeeds" do expect(build[2]).to be_success end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/last_run_spec.rb
spec/last_run_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::LastRun do subject { SimpleCov::LastRun } it "defines a last_run_path" do expect(subject.last_run_path).to include "tmp/coverage/.last_run.json" end it "writes json to its last_run_path that can be parsed again" do structure = [{"key" => "value"}] subject.write(structure) file_contents = File.read(subject.last_run_path) expect(JSON.parse(file_contents)).to eq structure end context "reading" do context "but the last_run file does not exist" do before { FileUtils.rm_f(subject.last_run_path) } it "returns nil" do expect(subject.read).to be_nil end end context "a non empty result" do before { subject.write([]) } it "reads json from its last_run_path" do expect(subject.read).to eq([]) end end context "an empty result" do before do File.open(subject.last_run_path, "w+") do |f| f.puts "" end end it "returns nil" do expect(subject.read).to be_nil end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/return_codes_spec.rb
spec/return_codes_spec.rb
# frozen_string_literal: true require "helper" # Make sure that exit codes of tests are propagated properly # See https://github.com/simplecov-ruby/simplecov/issues/5 describe "return codes" do context "inside fixtures/frameworks" do around do |test| Dir.chdir(File.join(File.dirname(__FILE__), "fixtures", "frameworks")) do FileUtils.rm_rf("./coverage") test.call end end before do @stdout, @stderr, @status = Open3.capture3(command) end shared_examples "good tests" do it "has a zero exit status" do expect(@status.exitstatus).to be_zero end it "prints nothing to STDERR" do expect(@stderr).to be_empty end end shared_examples "bad tests" do context "with default configuration" do it "has a non-zero exit status" do expect(@status.exitstatus).not_to be_zero end it "prints a message to STDERR" do # https://github.com/oracle/truffleruby/issues/3535 skip "fails on truffleruby" if RUBY_ENGINE == "truffleruby" && Object::Object::RUBY_ENGINE_VERSION < "24.1" && command.include?("testunit_bad.rb") expect(@stderr).to match(/stopped.+SimpleCov.+previous.+error/i) end end context "when print_error_status is disabled" do let(:command) { "PRINT_ERROR_STATUS=false #{super()}" } it "has a non-zero exit status" do expect(@status.exitstatus).not_to be_zero end it "does not print anything to STDERR" do expect(@stderr).to be_empty end end end context "when running testunit_good.rb" do let(:command) { "ruby testunit_good.rb" } it_behaves_like "good tests" end context "when running rspec_good.rb" do let(:command) { "rspec rspec_good.rb" } it_behaves_like "good tests" end context "when running testunit_bad.rb" do let(:command) { "ruby testunit_bad.rb" } it_behaves_like "bad tests" end context "when running rspec_bad.rb" do let(:command) { "rspec rspec_bad.rb" } it_behaves_like "bad tests" end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/result_merger_spec.rb
spec/result_merger_spec.rb
# frozen_string_literal: true require "helper" require "tempfile" require "timeout" describe SimpleCov::ResultMerger do after do FileUtils.rm_f(SimpleCov::ResultMerger.resultset_path) end let(:resultset1) do { source_fixture("sample.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil]}, source_fixture("app/models/user.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]}, source_fixture("app/controllers/sample_controller.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]}, source_fixture("resultset1.rb") => {"lines" => [1, 1, 1, 1]}, source_fixture("parallel_tests.rb") => {"lines" => [nil, 0, nil, 0]}, source_fixture("conditionally_loaded_1.rb") => {"lines" => [nil, 0, 1]} # loaded only in the first resultset } end let(:resultset2) do { source_fixture("sample.rb") => {"lines" => [1, nil, 1, 1, nil, nil, 1, 1, nil, nil]}, source_fixture("app/models/user.rb") => {"lines" => [nil, 1, 5, 1, nil, nil, 1, 0, nil, nil]}, source_fixture("app/controllers/sample_controller.rb") => {"lines" => [nil, 3, 1, nil, nil, nil, 1, 0, nil, nil]}, source_fixture("resultset2.rb") => {"lines" => [nil, 1, 1, nil]}, source_fixture("parallel_tests.rb") => {"lines" => [nil, nil, 0, 0]}, source_fixture("conditionally_loaded_2.rb") => {"lines" => [nil, 0, 1]} # loaded only in the second resultset } end let(:merged_resultset1_and2) do { source_fixture("sample.rb") => {"lines" => [1, 1, 2, 2, nil, nil, 2, 2, nil, nil]}, source_fixture("app/models/user.rb") => {"lines" => [nil, 2, 6, 2, nil, nil, 2, 0, nil, nil]}, source_fixture("app/controllers/sample_controller.rb") => {"lines" => [nil, 4, 2, 1, nil, nil, 2, 0, nil, nil]}, source_fixture("resultset1.rb") => {"lines" => [1, 1, 1, 1]}, source_fixture("parallel_tests.rb") => {"lines" => [nil, nil, nil, 0]}, source_fixture("conditionally_loaded_1.rb") => {"lines" => [nil, 0, 1]}, source_fixture("resultset2.rb") => {"lines" => [nil, 1, 1, nil]}, source_fixture("conditionally_loaded_2.rb") => {"lines" => [nil, 0, 1]} } end let(:result1) { SimpleCov::Result.new(resultset1, command_name: "result1") } let(:result2) { SimpleCov::Result.new(resultset2, command_name: "result2") } describe "resultset handling" do # See GitHub issue #6 it "returns an empty hash when the resultset cache file is empty" do File.open(SimpleCov::ResultMerger.resultset_path, "w+") { |f| f.puts "" } expect(SimpleCov::ResultMerger.read_resultset).to be_empty end # See GitHub issue #6 it "returns an empty hash when the resultset cache file is not present" do system "rm #{SimpleCov::ResultMerger.resultset_path}" if File.exist?(SimpleCov::ResultMerger.resultset_path) expect(SimpleCov::ResultMerger.read_resultset).to be_empty end end describe "basic workings with 2 resultsets" do before do system "rm #{SimpleCov::ResultMerger.resultset_path}" if File.exist?(SimpleCov::ResultMerger.resultset_path) SimpleCov::ResultMerger.store_result(result1) SimpleCov::ResultMerger.store_result(result2) end it "has stored data in resultset_path JSON file" do expect(File.readlines(SimpleCov::ResultMerger.resultset_path).length).to be > 50 end it "returns a hash containing keys ['result1' and 'result2'] for resultset" do expect(SimpleCov::ResultMerger.read_resultset.keys.sort).to eq %w[result1 result2] end it "returns proper values for merged_result" do result = SimpleCov::ResultMerger.merged_result expect_resultset_1_and_2_merged(result.to_hash) end context "with second result way above the merge_timeout" do let(:result2) { outdated(super()) } before do SimpleCov::ResultMerger.store_result(result2) end it "has only one result in SimpleCov::ResultMerger.results" do # second result does not appear in the merged results merged_coverage = SimpleCov::ResultMerger.merged_result expect(merged_coverage.command_name).to eq "result1" expect(merged_coverage.original_result).to eq resultset1 end end end describe ".merge_and_store" do let(:resultset_prefix) { "test_resultset" } let(:resultset1_path) { "#{resultset_prefix}1.json" } let(:resultset2_path) { "#{resultset_prefix}2.json" } describe "merging behavior" do before do store_result(result1, path: resultset1_path) store_result(result2, path: resultset2_path) end after do FileUtils.rm Dir.glob("#{resultset_prefix}*.json") end context "2 normal results" do it "correctly merges the 2 results" do result = SimpleCov::ResultMerger.merge_and_store(resultset1_path, resultset2_path) expect_resultset_1_and_2_merged(result.to_hash) end it "has the result stored" do SimpleCov::ResultMerger.merge_and_store(resultset1_path, resultset2_path) expect_resultset_1_and_2_merged(SimpleCov::ResultMerger.read_resultset) end end context "1 resultset is outdated" do let(:result1) { outdated(super()) } it "completely omits the result from the merge" do result_hash = SimpleCov::ResultMerger.merge_and_store(resultset1_path, resultset2_path).to_hash expect(result_hash.keys).to eq ["result2"] merged_coverage = result_hash.fetch("result2").fetch("coverage") expect(merged_coverage).to eq(resultset2) end it "includes it when we say ignore_timeout: true" do result_hash = SimpleCov::ResultMerger.merge_and_store(resultset1_path, resultset2_path, ignore_timeout: true).to_hash expect_resultset_1_and_2_merged(result_hash) end end context "both resultsets outdated" do let(:result1) { outdated(super()) } let(:result2) { outdated(super()) } it "completely omits the result from the merge" do allow(SimpleCov::ResultMerger).to receive(:store) result = SimpleCov::ResultMerger.merge_and_store(resultset1_path, resultset2_path) expect(result).to eq nil expect(SimpleCov::ResultMerger).not_to have_received(:store) end it "includes both when we say ignore_timeout: true" do result_hash = SimpleCov::ResultMerger.merge_and_store(resultset1_path, resultset2_path, ignore_timeout: true).to_hash expect_resultset_1_and_2_merged(result_hash) end end end context "pre 0.18 result format" do let(:file_path) { "old_resultset.json" } let(:content) { {source_fixture("three.rb") => [nil, 1, 2]} } before do data = { "some command name" => { "coverage" => content, "timestamp" => Time.now.to_i } } File.open(file_path, "w+") do |f| f.puts JSON.pretty_generate(data) end end after do FileUtils.rm file_path end it "gets the same content back but under \"lines\"" do result = SimpleCov::ResultMerger.merge_and_store(file_path) expect(result.original_result).to eq( source_fixture("three.rb") => {"lines" => [nil, 1, 2]} ) end end end describe ".store_result" do it "refreshes the resultset" do set = SimpleCov::ResultMerger.read_resultset SimpleCov::ResultMerger.store_result({}) new_set = SimpleCov::ResultMerger.read_resultset expect(new_set).not_to be(set) end it "persists to disk" do SimpleCov::ResultMerger.store_result("a" => [1]) new_set = SimpleCov::ResultMerger.read_resultset expect(new_set).to eq("a" => [1]) end it "synchronizes writes" do expect(SimpleCov::ResultMerger).to receive(:synchronize_resultset) SimpleCov::ResultMerger.store_result({}) end end describe ".resultset" do it "synchronizes reads" do expect(SimpleCov::ResultMerger).to receive(:synchronize_resultset) SimpleCov::ResultMerger.read_resultset end end describe ".synchronize_resultset" do it "is reentrant (i.e. doesn't block its own process)" do # without @resultset_locked, this spec would fail and # `.store_result` wouldn't work expect do Timeout.timeout(1) do SimpleCov::ResultMerger.synchronize_resultset do SimpleCov::ResultMerger.synchronize_resultset do # nothing end end end end.not_to raise_error end it "blocks other processes" do file = Tempfile.new("foo") test_script = <<-CODE require "simplecov" SimpleCov.coverage_dir(#{SimpleCov.coverage_dir.inspect}) # ensure the parent process has enough time to get a # lock before we do sleep 0.5 $stdout.sync = true puts "running" # see `sleep`s in parent process SimpleCov::ResultMerger.synchronize_resultset do File.open(#{file.path.inspect}, "a") { |f| f.write("process 2\n") } end CODE IO.popen("ruby -e #{Shellwords.escape(test_script)} 2>/dev/null") do |other_process| SimpleCov::ResultMerger.synchronize_resultset do # wait until the child process is going, and then wait some more # so we can be sure it blocks on the lock we already have. sleep 0.1 until other_process.gets == "running\n" sleep 1 # despite the sleeps, this will be written first since we got # the first lock File.open(file.path, "a") { |f| f.write("process 1\n") } end # wait for it to finish other_process.gets end expect(file.read).to eq("process 1\nprocess 2\n") end end private def store_result(result, path:) File.open(path, "w+") { |f| f.puts JSON.pretty_generate(result.to_hash) } end def outdated(result) result.created_at = Time.now - 172_800 result end def expect_resultset_1_and_2_merged(result_hash) merged_coverage = result_hash.fetch("result1, result2").fetch("coverage") expect(merged_coverage).to eq(merged_resultset1_and2) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/lines_classifier_spec.rb
spec/lines_classifier_spec.rb
# frozen_string_literal: true require "helper" require "simplecov/lines_classifier" describe SimpleCov::LinesClassifier do describe "#classify" do describe "relevant lines" do it "determines code as relevant" do classified_lines = subject.classify [ "module Foo", " class Baz", " def Bar", " puts 'hi'", " end", " end", "end" ] expect(classified_lines.length).to eq 7 expect(classified_lines).to all be_relevant end it "determines invalid UTF-8 byte sequences as relevant" do classified_lines = subject.classify [ "bytes = \"\xF1t\xEBrn\xE2ti\xF4n\xE0liz\xE6ti\xF8n\"" ] expect(classified_lines.length).to eq 1 expect(classified_lines).to all be_relevant end end describe "not-relevant lines" do it "determines whitespace is not-relevant" do classified_lines = subject.classify [ "", " ", "\t\t" ] expect(classified_lines.length).to eq 3 expect(classified_lines).to all be_irrelevant end describe "comments" do it "determines comments are not-relevant" do classified_lines = subject.classify [ "#Comment", " # Leading space comment", "\t# Leading tab comment" ] expect(classified_lines.length).to eq 3 expect(classified_lines).to all be_irrelevant end it "doesn't mistake interpolation as a comment" do classified_lines = subject.classify [ 'puts "#{var}"' # rubocop:disable Lint/InterpolationCheck ] expect(classified_lines.length).to eq 1 expect(classified_lines).to all be_relevant end end describe ":nocov: blocks" do it "determines :nocov: blocks are not-relevant" do classified_lines = subject.classify [ "# :nocov:", "def hi", "end", "# :nocov:" ] expect(classified_lines.length).to eq 4 expect(classified_lines).to all be_irrelevant end it "determines all lines after a non-closing :nocov: as not-relevant" do classified_lines = subject.classify [ "# :nocov:", "puts 'Not relevant'", "# :nocov:", "puts 'Relevant again'", "puts 'Still relevant'", "# :nocov:", "puts 'Not relevant till the end'", "puts 'Ditto'" ] expect(classified_lines.length).to eq 8 expect(classified_lines[0..2]).to all be_irrelevant expect(classified_lines[3..4]).to all be_relevant expect(classified_lines[5..7]).to all be_irrelevant end end end end RSpec::Matchers.define :be_relevant do match do |actual| actual == SimpleCov::LinesClassifier::RELEVANT end end RSpec::Matchers.define :be_irrelevant do match do |actual| actual == SimpleCov::LinesClassifier::NOT_RELEVANT end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/source_file_spec.rb
spec/source_file_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::SourceFile do COVERAGE_FOR_SAMPLE_RB = { "lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil, nil, 1, 0, nil, nil, nil], "branches" => {} }.freeze COVERAGE_FOR_SAMPLE_RB_WITH_MORE_LINES = { "lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil, nil, nil, nil, nil, nil, nil, nil] }.freeze context "a source file initialized with some coverage data" do subject do SimpleCov::SourceFile.new(source_fixture("sample.rb"), COVERAGE_FOR_SAMPLE_RB) end it "has a filename" do expect(subject.filename).not_to be_nil end it "has source equal to src" do expect(subject.src).to eq(subject.source) end it "has a project filename which removes the project directory" do expect(subject.project_filename).to eq("/spec/fixtures/sample.rb") end it "has source_lines equal to lines" do expect(subject.lines).to eq(subject.source_lines) end it "has 16 source lines" do expect(subject.lines.count).to eq(16) end it "has all source lines of type SimpleCov::SourceFile::Line" do subject.lines.each do |line| expect(line).to be_a SimpleCov::SourceFile::Line end end it "has 'class Foo' as line(2).source" do expect(subject.line(2).source).to eq("class Foo\n") end describe "line coverage" do it "returns lines number 2, 3, 4, 7 for covered_lines" do expect(subject.covered_lines.map(&:line)).to eq([2, 3, 4, 7]) end it "returns lines number 8 for missed_lines" do expect(subject.missed_lines.map(&:line)).to eq([8]) end it "returns lines number 1, 5, 6, 9, 10, 16 for never_lines" do expect(subject.never_lines.map(&:line)).to eq([1, 5, 6, 9, 10, 16]) end it "returns line numbers 11, 12, 13, 14, 15 for skipped_lines" do expect(subject.skipped_lines.map(&:line)).to eq([11, 12, 13, 14, 15]) end it "has 80% covered_percent" do expect(subject.covered_percent).to eq(80.0) end end describe "branch coverage" do it "has total branches count 0" do expect(subject.total_branches.size).to eq(0) end it "has covered branches count 0" do expect(subject.covered_branches.size).to eq(0) end it "has missed branches count 0" do expect(subject.missed_branches.size).to eq(0) end it "is considered 100% branches covered" do expect(subject.branches_coverage_percent).to eq(100.0) end it "has branch coverage report" do expect(subject.branches_report).to eq({}) end end end context "file with branches" do COVERAGE_FOR_BRANCHES_RB = { "lines" => [1, 1, 1, nil, 1, nil, 1, 0, nil, 1, nil, nil, nil], "branches" => { [:if, 0, 3, 4, 3, 21] => {[:then, 1, 3, 4, 3, 10] => 0, [:else, 2, 3, 4, 3, 21] => 1}, [:if, 3, 5, 4, 5, 26] => {[:then, 4, 5, 16, 5, 20] => 1, [:else, 5, 5, 23, 5, 26] => 0}, [:if, 6, 7, 4, 11, 7] => {[:then, 7, 8, 6, 8, 10] => 0, [:else, 8, 10, 6, 10, 9] => 1} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("branches.rb"), COVERAGE_FOR_BRANCHES_RB) end describe "branch coverage" do it "has 50% branch coverage" do expect(subject.branches_coverage_percent).to eq 50.0 end it "has total branches count 6" do expect(subject.total_branches.size).to eq(6) end it "has covered branches count 3" do expect(subject.covered_branches.size).to eq(3) end it "has missed branches count 3" do expect(subject.missed_branches.size).to eq(3) end it "has coverage report" do expect(subject.branches_report).to eq( 3 => [[:then, 0], [:else, 1]], 5 => [[:then, 1], [:else, 0]], 7 => [[:then, 0]], 9 => [[:else, 1]] ) end it "has line 7 with missed branches branch" do expect(subject.line_with_missed_branch?(7)).to eq(true) end it "has line 3 with missed branches branch" do expect(subject.line_with_missed_branch?(3)).to eq(true) end end describe "line coverage" do it "has line coverage" do expect(subject.covered_percent).to be_within(0.01).of(85.71) end it "has 6 covered lines" do expect(subject.covered_lines.size).to eq 6 end it "has 1 missed line" do expect(subject.missed_lines.size).to eq 1 end it "has 7 relevant lines" do expect(subject.relevant_lines).to eq 7 end end end context "simulating potential Ruby 1.9 defect -- see Issue #56" do subject do SimpleCov::SourceFile.new(source_fixture("sample.rb"), COVERAGE_FOR_SAMPLE_RB_WITH_MORE_LINES) end it "has 16 source lines regardless of extra data in coverage array" do # Do not litter test output with known warning capture_stderr { expect(subject.lines.count).to eq(16) } end it "prints a warning to stderr if coverage array contains more data than lines in the file" do captured_output = capture_stderr do subject.lines end expect(captured_output).to match(/^Warning: coverage data provided/) end end context "A file that has inline branches" do COVERAGE_FOR_INLINE = { "lines" => [1, 1, 1, nil, 1, 1, 0, nil, 1, nil, nil, nil, nil], "branches" => { [:if, 0, 3, 11, 3, 33] => {[:then, 1, 3, 23, 3, 27] => 1, [:else, 2, 3, 30, 3, 33] => 0}, [:if, 3, 6, 6, 10, 9] => {[:then, 4, 7, 8, 7, 12] => 0, [:else, 5, 9, 8, 9, 11] => 1} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("inline.rb"), COVERAGE_FOR_INLINE) end it "has branches report on 3 lines" do expect(subject.branches_report.keys.size).to eq(3) expect(subject.branches_report.keys).to eq([3, 6, 8]) end it "has covered branches count 2" do expect(subject.covered_branches.size).to eq(2) end it "has dual element in condition at line 3 report" do expect(subject.branches_report[3]).to eq([[:then, 1], [:else, 0]]) end it "has branches coverage percent 50.00" do expect(subject.branches_coverage_percent).to eq(50.00) end end context "a file that is never relevant" do COVERAGE_FOR_NEVER_RB = {"lines" => [nil, nil], "branches" => {}}.freeze subject do SimpleCov::SourceFile.new(source_fixture("never.rb"), COVERAGE_FOR_NEVER_RB) end it "has 0.0 covered_strength" do expect(subject.covered_strength).to eq 0.0 end it "has 100.0 covered_percent" do expect(subject.covered_percent).to eq 100.0 end it "has 100.0 branch coverage" do expect(subject.branches_coverage_percent).to eq(100.00) end end context "a file where nothing is ever executed mixed with skipping #563" do COVERAGE_FOR_SKIPPED_RB = {"lines" => [nil, nil, nil, nil]}.freeze subject do SimpleCov::SourceFile.new(source_fixture("skipped.rb"), COVERAGE_FOR_SKIPPED_RB) end it "has 0.0 covered_strength" do expect(subject.covered_strength).to eq 0.0 end it "has 0.0 covered_percent" do expect(subject.covered_percent).to eq 100.0 end end context "a file where everything is skipped and missed #563" do COVERAGE_FOR_SKIPPED_RB_2 = {"lines" => [nil, nil, 0, nil]}.freeze subject do SimpleCov::SourceFile.new(source_fixture("skipped.rb"), COVERAGE_FOR_SKIPPED_RB_2) end it "has 0.0 covered_strength" do expect(subject.covered_strength).to eq 0.0 end it "has 0.0 covered_percent" do expect(subject.covered_percent).to eq 100.0 end it "has no covered or missed lines" do expect(subject.covered_lines).to be_empty expect(subject.missed_lines).to be_empty end end context "a file where everything is skipped/irrelevant but executed #563" do COVERAGE_FOR_SKIPPED_AND_EXECUTED_RB = { "lines" => [nil, nil, 1, 1, 0, 0, nil, 0, nil, nil, nil, nil], "branches" => { [:if, 0, 5, 4, 9, 7] => {[:then, 1, 6, 6, 6, 7] => 1, [:else, 2, 8, 6, 8, 7] => 0} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("skipped_and_executed.rb"), COVERAGE_FOR_SKIPPED_AND_EXECUTED_RB) end describe "line coverage" do it "has no relevant lines" do expect(subject.relevant_lines).to eq(0) end it "has no covered lines" do expect(subject.covered_lines.size).to eq(0) end it "has no missed lines" do expect(subject.missed_lines.size).to eq(0) end it "has a whole lot of skipped lines" do expect(subject.skipped_lines.size).to eq(11) end it "has 0.0 covered_strength" do expect(subject.covered_strength).to eq 0.0 end it "has 0.0 covered_percent" do expect(subject.covered_percent).to eq 100.0 end end describe "branch coverage" do it "has an empty branch report" do expect(subject.branches_report).to eq({}) end it "has no branches" do expect(subject.total_branches.size).to eq 0 expect(subject.no_branches?).to eq true end it "does has neither covered nor missed branches" do expect(subject.missed_branches.size).to eq 0 expect(subject.covered_branches.size).to eq 0 end end end context "a file with more complex skipping" do COVERAGE_FOR_NOCOV_COMPLEX_RB = { "lines" => [nil, nil, 1, 1, nil, 1, nil, nil, nil, 1, nil, nil, 1, nil, nil, 0, nil, 1, nil, 0, nil, nil, 1, nil, nil, nil, nil], "branches" => { [:if, 0, 6, 4, 11, 7] => {[:then, 1, 7, 6, 7, 7] => 0, [:else, 2, 10, 6, 10, 7] => 1}, [:if, 3, 13, 4, 13, 24] => {[:then, 4, 13, 4, 13, 12] => 1, [:else, 5, 13, 4, 13, 24] => 0}, [:while, 6, 16, 4, 16, 27] => {[:body, 7, 16, 4, 16, 12] => 2}, [:case, 8, 18, 4, 24, 7] => { [:when, 9, 20, 6, 20, 11] => 0, [:when, 10, 23, 6, 23, 10] => 1, [:else, 11, 18, 4, 24, 7] => 0 } } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("nocov_complex.rb"), COVERAGE_FOR_NOCOV_COMPLEX_RB) end describe "line coverage" do it "has 6 relevant lines" do expect(subject.relevant_lines).to eq(5) end it "has 6 covered lines" do expect(subject.covered_lines.size).to eq(5) end it "has no missed lines" do expect(subject.missed_lines.size).to eq(0) end it "has a whole lot of skipped lines" do expect(subject.skipped_lines.size).to eq(11) end it "has 100.0 covered_percent" do expect(subject.covered_percent).to eq 100.0 end end describe "branch coverage" do it "has an empty branch report" do expect(subject.branches_report).to eq( 9 => [[:else, 1]], 13 => [[:then, 1], [:else, 0]], 22 => [[:when, 1]] ) end it "covers 3/4 branches" do expect(subject.total_branches.size).to eq 4 expect(subject.missed_branches.size).to eq 1 expect(subject.covered_branches.size).to eq 3 end end end context "a file with nested branches" do COVERAGE_FOR_NESTED_BRANCHES_RB = { "lines" => [nil, nil, 1, 1, 1, 1, 1, 1, nil, nil, 0, nil, nil, nil, nil], "branches" => { [:while, 0, 7, 8, 7, 31] => {[:body, 1, 7, 8, 7, 16] => 2}, [:if, 2, 6, 6, 9, 9] => {[:then, 3, 7, 8, 8, 11] => 1, [:else, 4, 6, 6, 9, 9] => 0}, [:if, 5, 5, 4, 12, 7] => {[:then, 6, 6, 6, 9, 9] => 1, [:else, 7, 11, 6, 11, 11] => 0} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("nested_branches.rb"), COVERAGE_FOR_NESTED_BRANCHES_RB) end describe "line coverage" do it "covers 6/7" do expect(subject.covered_percent).to be_within(0.01).of(85.71) end end describe "branch coverage" do it "covers 3/5" do expect(subject.total_branches.size).to eq 5 expect(subject.covered_branches.size).to eq 3 expect(subject.missed_branches.size).to eq 2 end it "registered 2 hits for the while branch" do expect(subject.branches_report[7]).to eq [[:body, 2]] end end end context "a file with case" do COVERAGE_FOR_CASE_STATEMENT_RB = { "lines" => [1, 1, 1, nil, 0, nil, 1, nil, 0, nil, 0, nil, nil, nil], "branches" => { [:case, 0, 3, 4, 12, 7] => { [:when, 1, 5, 6, 5, 10] => 0, [:when, 2, 7, 6, 7, 10] => 1, [:when, 3, 9, 6, 9, 10] => 0, [:else, 4, 11, 6, 11, 11] => 0 } } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("case.rb"), COVERAGE_FOR_CASE_STATEMENT_RB) end describe "line coverage" do it "covers 4/7" do expect(subject.relevant_lines).to eq 7 expect(subject.covered_lines.size).to eq 4 expect(subject.missed_lines.size).to eq 3 end end describe "branch coverage" do it "covers 1/4" do expect(subject.total_branches.size).to eq 4 expect(subject.covered_branches.size).to eq 1 expect(subject.missed_branches.size).to eq 3 end it "covers all the things right" do expect(subject.branches_report).to eq( 4 => [[:when, 0]], 6 => [[:when, 1]], 8 => [[:when, 0]], 10 => [[:else, 0]] ) end end end context "a file with case without else" do COVERAGE_FOR_CASE_WITHOUT_ELSE_STATEMENT_RB = { "lines" => [1, 1, 1, nil, 0, nil, 1, nil, 0, nil, nil, nil], "branches" => { [:case, 0, 3, 4, 10, 7] => { [:when, 1, 5, 6, 5, 10] => 0, [:when, 2, 7, 6, 7, 10] => 1, [:when, 3, 9, 6, 9, 10] => 0, [:else, 4, 3, 4, 10, 7] => 0 } } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("case_without_else.rb"), COVERAGE_FOR_CASE_WITHOUT_ELSE_STATEMENT_RB) end describe "line coverage" do it "covers 4/6" do expect(subject.relevant_lines).to eq 6 expect(subject.covered_lines.size).to eq 4 expect(subject.missed_lines.size).to eq 2 end end describe "branch coverage" do it "covers 1/4 (counting the else branch)" do expect(subject.total_branches.size).to eq 4 expect(subject.covered_branches.size).to eq 1 expect(subject.missed_branches.size).to eq 3 end it "marks the non declared else branch as missing at the point of the case" do expect(subject.branches_for_line(3)).to eq [[:else, 0]] end it "covers the branch that includes 42" do expect(subject.branches_report).to eq( 3 => [[:else, 0]], 4 => [[:when, 0]], 6 => [[:when, 1]], 8 => [[:when, 0]] ) end end end context "a file with if/elsif" do COVERAGE_FOR_ELSIF_RB = { "lines" => [1, 1, 1, 0, 1, 0, 1, 1, nil, 0, nil, nil, nil], "branches" => { [:if, 0, 7, 4, 10, 10] => {[:then, 1, 8, 6, 8, 10] => 1, [:else, 2, 10, 6, 10, 10] => 0}, [:if, 3, 5, 4, 10, 10] => {[:then, 4, 6, 6, 6, 10] => 0, [:else, 5, 7, 4, 10, 10] => 1}, [:if, 6, 3, 4, 11, 7] => {[:then, 7, 4, 6, 4, 10] => 0, [:else, 8, 5, 4, 10, 10] => 1} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("elsif.rb"), COVERAGE_FOR_ELSIF_RB) end describe "line coverage" do it "covers 6/9" do expect(subject.relevant_lines).to eq 9 expect(subject.covered_lines.size).to eq 6 expect(subject.missed_lines.size).to eq 3 end end describe "branch coverage" do it "covers 3/6" do expect(subject.total_branches.size).to eq 6 expect(subject.covered_branches.size).to eq 3 expect(subject.missed_branches.size).to eq 3 end it "covers the branch that includes 42" do expect(subject.branches_report[7]).to eq [[:then, 1]] end end end context "the branch tester script" do COVERAGE_FOR_BRANCH_TESTER_RB = { "lines" => [nil, nil, 1, 1, nil, 1, nil, 1, 1, nil, nil, 1, 0, nil, nil, 1, 0, nil, 1, nil, nil, 1, 1, 1, nil, nil, 1, 0, nil, nil, 1, 1, nil, 0, nil, 1, 1, 0, 0, 1, 5, 0, 0, nil, 0, nil, 0, nil, nil, nil], "branches" => { [:if, 0, 4, 0, 4, 19] => {[:then, 1, 4, 12, 4, 15] => 0, [:else, 2, 4, 18, 4, 19] => 1}, [:unless, 3, 6, 0, 6, 23] => {[:else, 4, 6, 0, 6, 23] => 0, [:then, 5, 6, 0, 6, 6] => 1}, [:unless, 6, 8, 0, 10, 3] => {[:else, 7, 8, 0, 10, 3] => 0, [:then, 8, 9, 2, 9, 14] => 1}, [:unless, 9, 12, 0, 14, 3] => {[:else, 10, 12, 0, 14, 3] => 1, [:then, 11, 13, 2, 13, 14] => 0}, [:unless, 12, 16, 0, 20, 3] => {[:else, 13, 19, 2, 19, 13] => 1, [:then, 14, 17, 2, 17, 14] => 0}, [:if, 15, 22, 0, 22, 19] => {[:then, 16, 22, 0, 22, 6] => 0, [:else, 17, 22, 0, 22, 19] => 1}, [:if, 18, 23, 0, 25, 3] => {[:then, 19, 24, 2, 24, 14] => 1, [:else, 20, 23, 0, 25, 3] => 0}, [:if, 21, 27, 0, 29, 3] => {[:then, 22, 28, 2, 28, 14] => 0, [:else, 23, 27, 0, 29, 3] => 1}, [:if, 24, 31, 0, 35, 3] => {[:then, 25, 32, 2, 32, 14] => 1, [:else, 26, 34, 2, 34, 13] => 0}, [:if, 27, 42, 0, 47, 8] => {[:then, 28, 43, 2, 45, 13] => 0, [:else, 29, 47, 2, 47, 8] => 0}, [:if, 30, 40, 0, 47, 8] => {[:then, 31, 41, 2, 41, 25] => 1, [:else, 32, 42, 0, 47, 8] => 0}, [:if, 33, 37, 0, 48, 3] => {[:then, 34, 38, 2, 39, 21] => 0, [:else, 35, 40, 0, 47, 8] => 1} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("branch_tester_script.rb"), COVERAGE_FOR_BRANCH_TESTER_RB) end describe "line coverage" do it "covers 18/28" do expect(subject.relevant_lines).to eq 28 expect(subject.covered_lines.size).to eq 18 end end describe "branch coverage" do it "covers 10/24" do expect(subject.total_branches.size).to eq 24 expect(subject.covered_branches.size).to eq 11 end it "notifies us of the missing else branch on line 27 that's hit" do expect(subject.branches_report[27]).to eq [[:then, 0], [:else, 1]] end end end context "a file entirely ignored with a single # :nocov:" do COVERAGE_FOR_SINGLE_NOCOV_RB = { "lines" => [nil, 1, 1, 1, 0, 1, 0, 1, 1, nil, 0, nil, nil, nil], "branches" => { [:if, 0, 8, 4, 11, 10] => {[:then, 1, 9, 6, 9, 10] => 1, [:else, 2, 11, 6, 11, 10] => 0}, [:if, 3, 6, 4, 11, 10] => {[:then, 4, 7, 6, 7, 10] => 0, [:else, 5, 8, 4, 11, 10] => 1}, [:if, 6, 4, 4, 12, 7] => {[:then, 7, 5, 6, 5, 10] => 0, [:else, 8, 6, 4, 11, 10] => 1} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("single_nocov.rb"), COVERAGE_FOR_SINGLE_NOCOV_RB) end describe "line coverage" do it "has all lines skipped" do expect(subject.skipped_lines.size).to eq(subject.lines.size) expect(subject.skipped_lines.size).to eq(14) end it "reports 100% coverage on 0/0" do expect(subject.covered_percent).to eq 100.0 expect(subject.relevant_lines).to eq 0 expect(subject.covered_lines.size).to eq 0 end end describe "branch coverage" do it "has 100% branch coverage on 0/0" do branch_coverage = subject.coverage_statistics.fetch(:branch) expect(branch_coverage.percent).to eq 100.0 expect(branch_coverage.total).to eq 0 expect(branch_coverage.covered).to eq 0 end it "has all branches marked as skipped" do expect(subject.branches.all?(&:skipped?)).to eq true end end end context "a file with an uneven usage of # :nocov:s" do COVERAGE_FOR_UNEVEN_NOCOV_RB = { "lines" => [1, 1, nil, 1, 0, 1, 0, nil, 1, 1, nil, nil, 0, nil, nil, nil], "branches" => { [:if, 0, 9, 4, 13, 10] => {[:then, 1, 10, 6, 10, 10] => 1, [:else, 2, 13, 6, 13, 10] => 0}, [:if, 3, 6, 4, 13, 10] => {[:then, 4, 7, 6, 7, 10] => 0, [:else, 5, 9, 4, 13, 10] => 1}, [:if, 6, 4, 4, 14, 7] => {[:then, 7, 5, 6, 5, 10] => 0, [:else, 8, 6, 4, 13, 10] => 1} } }.freeze subject do SimpleCov::SourceFile.new(source_fixture("uneven_nocovs.rb"), COVERAGE_FOR_UNEVEN_NOCOV_RB) end describe "line coverage" do it "has 12 lines skipped" do expect(subject.skipped_lines.size).to eq(12) end it "reports 100% coverage on 4/4" do expect(subject.covered_percent).to eq 100.0 expect(subject.relevant_lines).to eq 4 expect(subject.covered_lines.size).to eq 4 end end describe "branch coverage" do it "has 100% branch coverage on 1/1" do branch_coverage = subject.coverage_statistics.fetch(:branch) expect(branch_coverage.percent).to eq 100.0 expect(branch_coverage.total).to eq 1 expect(branch_coverage.covered).to eq 1 end it "has 5 branches marked as skipped" do expect(subject.branches.select(&:skipped?).size).to eq 5 end end end context "a file contains non-ASCII characters" do COVERAGE_FOR_SINGLE_LINE = {"lines" => [nil]}.freeze COVERAGE_FOR_DOUBLE_LINES = {"lines" => [nil, 1]}.freeze COVERAGE_FOR_TRIPLE_LINES = {"lines" => [nil, nil, 1]}.freeze DEGREE_135_LINE = "puts \"135°C\"\n" shared_examples_for "converting to UTF-8" do it "has all source lines of encoding UTF-8" do subject.lines.each do |line| expect(line.source.encoding).to eq(Encoding::UTF_8) expect(line.source).to be_valid_encoding end end end describe "UTF-8 without magic comment" do subject do SimpleCov::SourceFile.new(source_fixture("utf-8.rb"), COVERAGE_FOR_SINGLE_LINE) end it_behaves_like "converting to UTF-8" it "has the line with 135°C" do expect(subject.line(1).source).to eq DEGREE_135_LINE end end describe "UTF-8 with magic comment" do subject do SimpleCov::SourceFile.new(source_fixture("utf-8-magic.rb"), COVERAGE_FOR_DOUBLE_LINES) end it_behaves_like "converting to UTF-8" it "has the line with 135°C" do expect(subject.line(2).source).to eq DEGREE_135_LINE end end describe "EUC-JP with magic comment" do subject do SimpleCov::SourceFile.new(source_fixture("euc-jp.rb"), COVERAGE_FOR_DOUBLE_LINES) end it_behaves_like "converting to UTF-8" it "has the line with 135°C" do expect(subject.line(2).source).to eq DEGREE_135_LINE end end describe "EUC-JP with magic comment and shebang" do subject do SimpleCov::SourceFile.new(source_fixture("euc-jp-shebang.rb"), COVERAGE_FOR_TRIPLE_LINES) end it_behaves_like "converting to UTF-8" it "has all the right lines" do expect(subject.lines.map(&:source)).to eq [ "#!/usr/bin/env ruby\n", "# encoding: EUC-JP\n", DEGREE_135_LINE ] end end describe "empty euc-jp file" do subject do SimpleCov::SourceFile.new(source_fixture("empty_euc-jp.rb"), "lines" => []) end it "has empty lines" do expect(subject.lines).to be_empty end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/config_loader_spec.rb
spec/config_loader_spec.rb
# frozen_string_literal: true require "helper" describe "loading config" do context "without ENV[HOME]" do it "does not raise any errors" do home = ENV.delete("HOME") begin expect { load "simplecov/load_global_config.rb" }.not_to raise_error ensure ENV["HOME"] = home end end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/helper.rb
spec/helper.rb
# frozen_string_literal: true require "rspec" require "stringio" require "open3" # loaded before simplecov to also capture parse time warnings require "support/fail_rspec_on_ruby_warning" require "simplecov" SimpleCov.coverage_dir("tmp/coverage") def source_fixture(filename) File.join(source_fixture_base_directory, "fixtures", filename) end def source_fixture_base_directory @source_fixture_base_directory ||= File.dirname(__FILE__) end # Taken from http://stackoverflow.com/questions/4459330/how-do-i-temporarily-redirect-stderr-in-ruby def capture_stderr # The output stream must be an IO-like object. In this case we capture it in # an in-memory IO object so we can return the string value. You can assign any # IO object here. previous_stderr = $stderr $stderr = StringIO.new yield $stderr.string ensure # Restore the previous value of stderr (typically equal to STDERR). $stderr = previous_stderr end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/deleted_source_spec.rb
spec/deleted_source_spec.rb
# frozen_string_literal: true require "helper" # Test to verify correct handling of deleted files # See https://github.com/simplecov-ruby/simplecov/issues/9 describe "A source file which is subsequently deleted" do it "does not cause an error" do Dir.chdir(File.join(File.dirname(__FILE__), "fixtures")) do `ruby deleted_source_sample.rb` expect($?.exitstatus).to be_zero end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/defaults_spec.rb
spec/defaults_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov do skip "requires the default configuration" if ENV["SIMPLECOV_NO_DEFAULTS"] context "profiles" do let(:config_class) do Class.new do include SimpleCov::Configuration def load_profile(name) configure(&SimpleCov.profiles[name.to_sym]) end end end let(:config) { config_class.new } def filtered?(config, filename) path = File.join(SimpleCov.root, filename) file = SimpleCov::SourceFile.new(path, [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]) config.filters.any? { |filter| filter.matches?(file) } end it "provides a sensible test_frameworks profile" do config.load_profile(:test_frameworks) expect(filtered?(config, "foo.rb")).not_to be expect(filtered?(config, "test/foo.rb")).to be expect(filtered?(config, "spec/bar.rb")).to be end it "provides a sensible rails profile" do config.load_profile(:rails) expect(filtered?(config, "app/models/user.rb")).not_to be expect(filtered?(config, "db/schema.rb")).to be expect(filtered?(config, "config/environment.rb")).to be end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/useless_results_remover_spec.rb
spec/useless_results_remover_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::UselessResultsRemover do subject do SimpleCov::UselessResultsRemover.call(result_set) end let(:gem_file_path) { "usr/bin/lib/2.5.0/gems/sample-gem/sample.rb" } let(:source_path) { source_fixture("app/models/user.rb") } let(:result_set) do { gem_file_path => { "lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil], "branches" => {[:if, 3, 8, 6, 8, 36] => {[:then, 4, 8, 6, 8, 12] => 47, [:else, 5, 8, 6, 8, 36] => 24}} }, source_path => { "lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil], "branches" => {[:if, 3, 8, 6, 8, 36] => {[:then, 4, 8, 6, 8, 12] => 47, [:else, 5, 8, 6, 8, 36] => 24}} } } end it "Result ignore gem file path from result set" do expect(result_set[gem_file_path]).to be_a(Hash) expect(subject).not_to have_key(gem_file_path) end it "still retains the app path" do expect(subject).to have_key(source_path) expect(subject[source_path]["lines"]).to be_a(Array) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/simplecov_spec.rb
spec/simplecov_spec.rb
# frozen_string_literal: true require "helper" require "coverage" describe SimpleCov do describe ".result" do before do SimpleCov.clear_result allow(Coverage).to receive(:result).once.and_return({}) end context "with merging disabled" do before do allow(SimpleCov).to receive(:use_merging).once.and_return(false) expect(SimpleCov).not_to receive(:wait_for_other_processes) end context "when not running" do before do allow(SimpleCov).to receive(:running).and_return(false) end it "returns nil" do expect(SimpleCov.result).to be_nil end end context "when running" do before do allow(SimpleCov).to receive(:running).and_return(true, false) end it "uses the result from Coverage" do expect(Coverage).to receive(:result).once.and_return(__FILE__ => [0, 1]) expect(SimpleCov.result.filenames).to eq [__FILE__] end it "adds not-loaded-files" do expect(SimpleCov).to receive(:add_not_loaded_files).once.and_return({}) SimpleCov.result end it "doesn't store the current coverage" do expect(SimpleCov::ResultMerger).not_to receive(:store_result) SimpleCov.result end it "doesn't merge the result" do expect(SimpleCov::ResultMerger).not_to receive(:merged_result) SimpleCov.result end it "caches its result" do result = SimpleCov.result expect(SimpleCov.result).to be(result) end end end context "with merging enabled" do let(:the_merged_result) { double } before do allow(SimpleCov).to receive(:use_merging).once.and_return(true) allow(SimpleCov::ResultMerger).to receive(:store_result).once allow(SimpleCov::ResultMerger).to receive(:merged_result).once.and_return(the_merged_result) expect(SimpleCov).to receive(:wait_for_other_processes) end context "when not running" do before do allow(SimpleCov).to receive(:running).and_return(false) end it "merges the result" do expect(SimpleCov.result).to be(the_merged_result) end end context "when running" do before do allow(SimpleCov).to receive(:running).and_return(true, false) end it "uses the result from Coverage" do expect(Coverage).to receive(:result).once.and_return({}) SimpleCov.result end it "adds not-loaded-files" do expect(SimpleCov).to receive(:add_not_loaded_files).once.and_return({}) SimpleCov.result end it "stores the current coverage" do expect(SimpleCov::ResultMerger).to receive(:store_result).once SimpleCov.result end it "merges the result" do expect(SimpleCov.result).to be(the_merged_result) end it "caches its result" do result = SimpleCov.result expect(SimpleCov.result).to be(result) end end end end describe ".exit_status_from_exception" do context "when no exception has occurred" do it "returns nil" do expect(SimpleCov.exit_status_from_exception).to eq(nil) end end context "when a SystemExit has occurred" do it "returns the SystemExit status" do raise SystemExit, 1 rescue SystemExit expect(SimpleCov.exit_status_from_exception).to eq(1) end end context "when a non SystemExit occurs" do it "return SimpleCov::ExitCodes::EXCEPTION" do raise "no system exit" rescue StandardError expect(SimpleCov.exit_status_from_exception).to eq(SimpleCov::ExitCodes::EXCEPTION) end end end describe ".process_result" do let(:result) { SimpleCov::Result.new({}) } context "when minimum coverage is 100%" do before do allow(SimpleCov).to receive(:minimum_coverage).and_return(line: 100) allow(SimpleCov).to receive(:result?).and_return(true) end context "when actual coverage is almost 100%" do before do allow(result).to receive(:coverage_statistics).and_return(line: double("statistics", percent: 100 * 32_847.0 / 32_848)) end it "return SimpleCov::ExitCodes::MINIMUM_COVERAGE" do expect( SimpleCov.process_result(result) ).to eq(SimpleCov::ExitCodes::MINIMUM_COVERAGE) end end context "when actual coverage is exactly 100%" do before do allow(result).to receive(:covered_percent).and_return(100.0) allow(result).to receive(:coverage_statistics).and_return( line: double("statistics", percent: 100.0) ) allow(result).to receive(:covered_percentages).and_return([]) allow(SimpleCov::LastRun).to receive(:read).and_return(nil) end it "return SimpleCov::ExitCodes::SUCCESS" do expect( SimpleCov.process_result(result) ).to eq(SimpleCov::ExitCodes::SUCCESS) end end context "branch coverage" do before do allow(SimpleCov).to receive(:minimum_coverage).and_return(branch: 90) allow(SimpleCov).to receive(:result?).and_return(true) end it "errors out when the coverage is too low" do allow(result).to receive(:coverage_statistics).and_return(branch: double("statistics", percent: 89.99)) expect( SimpleCov.process_result(result) ).to eq(SimpleCov::ExitCodes::MINIMUM_COVERAGE) end end end end describe ".collate" do let(:resultset1) do {source_fixture("sample.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil]}} end let(:resultset2) do {source_fixture("sample.rb") => {"lines" => [1, nil, 1, 1, nil, nil, 1, 1, nil, nil]}} end let(:resultset_path) { SimpleCov::ResultMerger.resultset_path } let(:resultset_folder) { File.dirname(resultset_path) } let(:merged_result) do { "result1, result2" => { "coverage" => { source_fixture("sample.rb") => { "lines" => [1, 1, 2, 2, nil, nil, 2, 2, nil, nil] } } } } end let(:collated) do JSON.parse(File.read(resultset_path)).transform_values { |v| v.reject { |k| k == "timestamp" } } end context "when no files to be merged" do it "shows an error message" do expect do glob = Dir.glob("#{resultset_folder}/*.final", File::FNM_DOTMATCH) SimpleCov.collate glob end.to raise_error("There are no reports to be merged") end end context "when files to be merged" do before do expect(SimpleCov).to receive(:run_exit_tasks!) end context "and a single report to be merged" do before do create_mergeable_report("result1", resultset1) end after do clear_mergeable_reports end it "creates a merged report identical to the original" do glob = Dir.glob("#{resultset_folder}/*.final", File::FNM_DOTMATCH) SimpleCov.collate glob expected = {"result1" => {"coverage" => resultset1}} expect(collated).to eq(expected) end end context "and multiple reports to be merged" do before do create_mergeable_report("result1", resultset1) create_mergeable_report("result2", resultset2) end after do clear_mergeable_reports end it "creates a merged report" do glob = Dir.glob("#{resultset_folder}/*.final", File::FNM_DOTMATCH) SimpleCov.collate glob expect(collated).to eq(merged_result) end end context "and multiple reports to be merged, one of them outdated" do before do create_mergeable_report("result1", resultset1) create_mergeable_report("result2", resultset2, outdated: true) end after do clear_mergeable_reports end it "ignores timeout by default creating a report with all values" do glob = Dir.glob("#{resultset_folder}/*.final", File::FNM_DOTMATCH) SimpleCov.collate glob expect(collated).to eq(merged_result) end it "creates a merged report with only the results from the current resultset if ignore_timeout: false" do glob = Dir.glob("#{resultset_folder}/*.final", File::FNM_DOTMATCH) SimpleCov.collate glob, ignore_timeout: false expected = {"result1" => {"coverage" => resultset1}} expect(collated).to eq(expected) end end private def create_mergeable_report(name, resultset, outdated: false) result = SimpleCov::Result.new(resultset) result.command_name = name result.created_at = Time.now - 172_800 if outdated SimpleCov::ResultMerger.store_result(result) FileUtils.mv resultset_path, "#{resultset_path}#{name}.final" end def clear_mergeable_reports SimpleCov.clear_result FileUtils.rm Dir.glob("#{resultset_path}*") end def expect_merged expected = {"result1, result2" => {"coverage" => {source_fixture("sample.rb") => {"lines" => [1, 1, 2, 2, nil, nil, 2, 2, nil, nil]}}}} expect(collated).to eq(expected) end end end # Normally wouldn't test private methods but just start has side effects that # cause errors so for time this is pragmatic (tm) describe ".start_coverage_measurement", if: SimpleCov.coverage_start_arguments_supported? do after do # SimpleCov is a Singleton/global object so once any test enables # any kind of coverage data it stays there. # Hence, we use clear_coverage_data to create a "clean slate" for these tests SimpleCov.clear_coverage_criteria end it "starts coverage in lines mode by default" do expect(Coverage).to receive(:start).with({lines: true}) SimpleCov.send :start_coverage_measurement end it "starts coverage with lines and branches if branches is activated" do expect(Coverage).to receive(:start).with({lines: true, branches: true}) SimpleCov.enable_coverage :branch SimpleCov.send :start_coverage_measurement end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/support/fail_rspec_on_ruby_warning.rb
spec/support/fail_rspec_on_ruby_warning.rb
# frozen_string_literal: true # Borrowed and heavily adjusted from: # https://github.com/metricfu/metric_fu/blob/master/spec/capture_warnings.rb require "fileutils" class FailOnWarnings def initialize @stderr_stream = StringIO.new @app_root = Dir.pwd end def collect_warnings $stderr = @stderr_stream $VERBOSE = true end def process_warnings lines = close_stream app_warnings, other_warnings = split_lines(lines) print_own_warnings(app_warnings) if app_warnings.any? write_other_warnings_to_tmp(other_warnings) if other_warnings.any? fail_script(app_warnings) if app_warnings.any? end private def close_stream $stderr = STDERR @stderr_stream.rewind lines = @stderr_stream.read.split("\n") lines.uniq! @stderr_stream.close lines end def split_lines(lines) lines.partition { |line| line.include?(@app_root) } end def print_own_warnings(app_warnings) puts "" puts "" puts <<-WARNINGS #{'-' * 30} app warnings: #{'-' * 30} #{app_warnings.join("\n")} #{'-' * 75} WARNINGS end def write_other_warnings_to_tmp(other_warnings) output_dir = File.join(@app_root, "tmp") FileUtils.mkdir_p(output_dir) output_file = File.join(output_dir, "warnings.txt") File.write(output_file, other_warnings.join("\n") << "\n") puts puts "Non-app warnings written to tmp/warnings.txt" puts end def fail_script(app_warnings) abort "Failing build due to app warnings: #{app_warnings.inspect}" end end warning_collector = FailOnWarnings.new warning_collector.collect_warnings RSpec.configure do |config| config.after(:suite) do warning_collector.process_warnings end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/exit_codes/minimum_coverage_by_file_check_spec.rb
spec/exit_codes/minimum_coverage_by_file_check_spec.rb
# frozen_string_literal: true require "helper" RSpec.describe SimpleCov::ExitCodes::MinimumCoverageByFileCheck do subject { described_class.new(result, minimum_coverage_by_file) } let(:result) do instance_double(SimpleCov::Result, coverage_statistics_by_file: stats) end let(:stats) do { line: [SimpleCov::CoverageStatistics.new(covered: 8, missed: 2)] } end context "all files passing requirements" do let(:minimum_coverage_by_file) { {line: 80} } it { is_expected.not_to be_failing } end context "one file violating requirements" do let(:minimum_coverage_by_file) { {line: 90} } it { is_expected.to be_failing } end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/exit_codes/minimum_overall_coverage_check_spec.rb
spec/exit_codes/minimum_overall_coverage_check_spec.rb
# frozen_string_literal: true require "helper" RSpec.describe SimpleCov::ExitCodes::MinimumOverallCoverageCheck do subject { described_class.new(result, minimum_coverage) } let(:result) do instance_double(SimpleCov::Result, coverage_statistics: stats) end let(:stats) do { line: SimpleCov::CoverageStatistics.new(covered: 8, missed: 2), branch: SimpleCov::CoverageStatistics.new(covered: 8, missed: 2) } end context "everything exactly ok" do let(:minimum_coverage) { {line: 80.0} } it { is_expected.not_to be_failing } end context "coverage violated" do let(:minimum_coverage) { {line: 90.0} } it { is_expected.to be_failing } end context "coverage slightly violated" do let(:minimum_coverage) { {line: 80.01} } it { is_expected.to be_failing } end context "one criterion violated" do let(:minimum_coverage) { {line: 80.0, branch: 90.0} } it { is_expected.to be_failing } end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/exit_codes/maximum_coverage_drop_check_spec.rb
spec/exit_codes/maximum_coverage_drop_check_spec.rb
# frozen_string_literal: true require "helper" RSpec.describe SimpleCov::ExitCodes::MaximumCoverageDropCheck do subject { described_class.new(result, maximum_coverage_drop) } let(:result) do instance_double(SimpleCov::Result, coverage_statistics: stats) end let(:stats) do { line: SimpleCov::CoverageStatistics.new(covered: 8, missed: 2), branch: SimpleCov::CoverageStatistics.new(covered: 8, missed: 2) } end let(:last_run) do { result: last_coverage } end let(:last_coverage) { {line: 80.0, branch: 80.0} } let(:maximum_coverage_drop) { {line: 0, branch: 0} } before do expect(SimpleCov::LastRun).to receive(:read).and_return(last_run) end context "we're at the same coverage" do it { is_expected.not_to be_failing } end context "more coverage drop allowed" do let(:maximum_coverage_drop) { {line: 10, branch: 10} } it { is_expected.not_to be_failing } end context "last coverage lower then new coverage" do let(:last_coverage) { {line: 70.0, branch: 70.0} } it { is_expected.not_to be_failing } end context "last coverage higher than new coverage" do let(:last_coverage) { {line: 80.01, branch: 80.01} } it { is_expected.to be_failing } context "but allowed drop is within range" do let(:maximum_coverage_drop) { {line: 0.01, branch: 0.01} } it { is_expected.not_to be_failing } end end context "one coverage lower than maximum drop" do let(:last_coverage) { {line: 80.01, branch: 70.0} } it { is_expected.to be_failing } context "but allowed drop is within range" do let(:maximum_coverage_drop) { {line: 0.01} } it { is_expected.not_to be_failing } end end context "coverage expectation for a coverage that wasn't previously present" do let(:last_coverage) { {line: 80.0} } let(:maximum_coverage_drop) { {line: 0, branch: 0} } it { is_expected.not_to be_failing } end context "no last run coverage information" do let(:last_run) { nil } it { is_expected.not_to be_failing } end context "old last_run.json format" do let(:last_run) do { # this format only considers line coverage result: {covered_percent: 80.0} } end it { is_expected.not_to be_failing } end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/combine/results_combiner_spec.rb
spec/combine/results_combiner_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::Combine::ResultsCombiner do describe "with two faked coverage resultsets" do let(:resultset1) do { source_fixture("sample.rb") => { "lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil], "branches" => {[:if, 3, 8, 6, 8, 36] => {[:then, 4, 8, 6, 8, 12] => 47, [:else, 5, 8, 6, 8, 36] => 24}} }, source_fixture("app/models/user.rb") => { "lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil], "branches" => {[:if, 3, 8, 6, 8, 36] => {[:then, 4, 8, 6, 8, 12] => 47, [:else, 5, 8, 6, 8, 36] => 24}} }, source_fixture("app/controllers/sample_controller.rb") => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]}, source_fixture("resultset1.rb") => {"lines" => [1, 1, 1, 1]}, source_fixture("parallel_tests.rb") => {"lines" => [nil, 0, nil, 0]}, source_fixture("conditionally_loaded_1.rb") => {"lines" => [nil, 0, 1]}, # loaded only in the first resultset source_fixture("three.rb") => {"lines" => [nil, 1, 1]} } end let(:resultset2) do { source_fixture("sample.rb") => {"lines" => [1, nil, 1, 1, nil, nil, 1, 1, nil, nil]}, source_fixture("app/models/user.rb") => { "lines" => [nil, 1, 5, 1, nil, nil, 1, 0, nil, nil], "branches" => {[:if, 3, 8, 6, 8, 36] => {[:then, 4, 8, 6, 8, 12] => 1, [:else, 5, 8, 6, 8, 36] => 2}} }, source_fixture("app/controllers/sample_controller.rb") => {"lines" => [nil, 3, 1, nil, nil, nil, 1, 0, nil, nil]}, source_fixture("resultset2.rb") => {"lines" => [nil, 1, 1, nil]}, source_fixture("parallel_tests.rb") => {"lines" => [nil, nil, 0, 0]}, source_fixture("conditionally_loaded_2.rb") => {"lines" => [nil, 0, 1]}, # loaded only in the second resultset source_fixture("three.rb") => {"lines" => [nil, 1, 4]} } end let(:resultset3) do {source_fixture("three.rb") => {"lines" => [nil, 1, 2]}} end after do SimpleCov.clear_coverage_criteria end before do SimpleCov.enable_coverage :branch end context "a merge" do subject do SimpleCov::Combine::ResultsCombiner.combine(resultset1, resultset2, resultset3) end it "has proper results for sample.rb" do expect(subject[source_fixture("sample.rb")]["lines"]).to eq([1, 1, 2, 2, nil, nil, 2, 2, nil, nil]) # gotta configure max line so it doesn't get ridiculous # rubocop:disable Style/IfUnlessModifier if SimpleCov.branch_coverage_supported? expect(subject[source_fixture("sample.rb")]["branches"][[:if, 3, 8, 6, 8, 36]][[:then, 4, 8, 6, 8, 12]]).to eq(47) end # rubocop:enable Style/IfUnlessModifier end it "has proper results for user.rb" do expect(subject[source_fixture("app/models/user.rb")]["lines"]).to eq([nil, 2, 6, 2, nil, nil, 2, 0, nil, nil]) if SimpleCov.branch_coverage_supported? expect(subject[source_fixture("app/models/user.rb")]["branches"][[:if, 3, 8, 6, 8, 36]][[:then, 4, 8, 6, 8, 12]]).to eq(48) expect(subject[source_fixture("app/models/user.rb")]["branches"][[:if, 3, 8, 6, 8, 36]][[:else, 5, 8, 6, 8, 36]]).to eq(26) end end it "has proper results for sample_controller.rb" do expect(subject[source_fixture("app/controllers/sample_controller.rb")]["lines"]).to eq([nil, 4, 2, 1, nil, nil, 2, 0, nil, nil]) end it "has proper results for resultset1.rb" do expect(subject[source_fixture("resultset1.rb")]["lines"]).to eq([1, 1, 1, 1]) end it "has proper results for resultset2.rb" do expect(subject[source_fixture("resultset2.rb")]["lines"]).to eq([nil, 1, 1, nil]) end it "has proper results for parallel_tests.rb" do expect(subject[source_fixture("parallel_tests.rb")]["lines"]).to eq([nil, nil, nil, 0]) end it "has proper results for conditionally_loaded_1.rb" do expect(subject[source_fixture("conditionally_loaded_1.rb")]["lines"]).to eq([nil, 0, 1]) end it "has proper results for conditionally_loaded_2.rb" do expect(subject[source_fixture("conditionally_loaded_2.rb")]["lines"]).to eq([nil, 0, 1]) end it "has proper results for three.rb" do expect(subject[source_fixture("three.rb")]["lines"]).to eq([nil, 3, 7]) end it "always returns a Hash object for branches", if: SimpleCov.branch_coverage_supported? do expect(subject[source_fixture("three.rb")]["branches"]).to eq({}) end end end it "merges frozen resultsets" do resultset1 = { source_fixture("sample.rb").freeze => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 1, nil, nil]}, source_fixture("app/models/user.rb").freeze => {"lines" => [nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]} } resultset2 = { source_fixture("sample.rb").freeze => {"lines" => [1, nil, 1, 1, nil, nil, 1, 1, nil, nil]} } merged_result = SimpleCov::Combine::ResultsCombiner.combine(resultset1, resultset2) expect(merged_result.keys).to eq(resultset1.keys) expect(merged_result.values.map(&:frozen?)).to eq([false, false]) expect(merged_result[source_fixture("sample.rb")]["lines"]).to eq([1, 1, 2, 2, nil, nil, 2, 2, nil, nil]) expect(merged_result[source_fixture("app/models/user.rb")]["lines"]).to eq([nil, 1, 1, 1, nil, nil, 1, 0, nil, nil]) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/resultset2.rb
spec/fixtures/resultset2.rb
class Resultset VERSION = 2 end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/branches.rb
spec/fixtures/branches.rb
class Branches def call(arg) return if arg < 0 _val = (arg == 42 ? :yes : :no) if arg.odd? :yes else :no end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/inline.rb
spec/fixtures/inline.rb
class Inline def call(arg) String(arg == 42 ? :yes : :no) String( if arg.odd? :yes else :no end ) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/nocov_complex.rb
spec/fixtures/nocov_complex.rb
# So much skippping # rubocop:disable Metrics/MethodLength, Lint/Void module NoCovComplex def self.call(arg) # :nocov: if arg == 42 0 # :nocov: else puts "yolo" end arg += 1 if arg.odd? # :nocov: arg -= 1 while arg > 40 case arg when 1..20 :nope # :nocov: when 30..40 :yas end end end # rubocop:enable Metrics/MethodLength, Lint/Void
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/parallel_tests.rb
spec/fixtures/parallel_tests.rb
# foo puts "foo" # bar puts "bar"
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/uneven_nocovs.rb
spec/fixtures/uneven_nocovs.rb
module UnevenNocov def self.call(arg) # :nocov: if arg.odd? :odd elsif arg == 30 :mop # :nocov: elsif arg == 42 :yay # :nocov: else :nay end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/nested_branches.rb
spec/fixtures/nested_branches.rb
# yes rubocop you are right but I want to test nesting! # rubocop:disable Metrics/BlockNesting module NestedBranches def self.call(arg) if arg.even? if arg == 42 arg -= 1 while arg > 40 :ok end else :nope end end end # rubocop:enable Metrics/BlockNesting
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/resultset1.rb
spec/fixtures/resultset1.rb
puts "foo" puts "foo" puts "foo" puts "foo"
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/skipped_and_executed.rb
spec/fixtures/skipped_and_executed.rb
# So much skipping # :nocov: class Foo def bar(arg) if arg == 42 0 else 1 end end end # :nocov:
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/empty_euc-jp.rb
spec/fixtures/empty_euc-jp.rb
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/deleted_source_sample.rb
spec/fixtures/deleted_source_sample.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "..")) require "lib/simplecov" SimpleCov.start { command_name "Test" } dir = __dir__ file = File.join(dir, "generated_buddha.rb") code = %{ def kill_the_buddha(z) z**z end } File.open(file, "w") { |f| f.print code } load file File.unlink file raise unless kill_the_buddha(3) == 27
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/coverer.rb
spec/fixtures/coverer.rb
# Script to gather coverage data to use in tests to go along with fixtures require "coverage" Coverage.start(:all) require_relative "uneven_nocovs" UnevenNocov.call(42) p Coverage.result
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/case.rb
spec/fixtures/case.rb
module Case def self.call(arg) case arg when 0...23 :foo when 40..50 :bar when Integer :baz else :nope end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/conditionally_loaded_2.rb
spec/fixtures/conditionally_loaded_2.rb
# some comment puts "wargh" puts "wargh 2"
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/sample.rb
spec/fixtures/sample.rb
# Foo class class Foo def initialize @foo = "baz" end def bar @foo end # :nocov: def skipped @foo * 2 end # :nocov: end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/elsif.rb
spec/fixtures/elsif.rb
module Elsif def self.call(arg) if arg.odd? :odd elsif arg == 30 :mop elsif arg == 42 :yay else :nay end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/never.rb
spec/fixtures/never.rb
# This class is purely some # comments
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/case_without_else.rb
spec/fixtures/case_without_else.rb
module Case def self.call(arg) case arg when 0...23 :foo when 40..50 :bar when Integer :baz end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/utf-8-magic.rb
spec/fixtures/utf-8-magic.rb
# encoding: UTF-8 puts "135°C"
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/utf-8.rb
spec/fixtures/utf-8.rb
puts "135°C"
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/conditionally_loaded_1.rb
spec/fixtures/conditionally_loaded_1.rb
# some comment puts "wargh" puts "wargh 1"
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/single_nocov.rb
spec/fixtures/single_nocov.rb
# :nocov: module SingleNocov def self.call(arg) if arg.odd? :odd elsif arg == 30 :mop elsif arg == 42 :yay else :nay end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/branch_tester_script.rb
spec/fixtures/branch_tester_script.rb
# Adapted from https://github.com/simplecov-ruby/simplecov/pull/694#issuecomment-562097006 # rubocop:disable all x = 1 x.eql?(4) ? "4" : x puts x unless x.eql?(5) unless x == 5 puts "Ola.." end unless x != 5 puts "Ola.." end unless x != 5 puts "Ola.." else puts "text" end puts x if x.eql?(5) if x != 5 puts "Ola.." end if x == 5 puts "Ola.." end if x != 5 puts "Ola.." else puts "text" end x = 4 if x == 1 puts "wow 1" puts "such excite!" elsif x == 4 4.times { puts "4!!!!"} elsif x == 14 puts "magic" puts "very" else puts x end # rubocop:enable all
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/skipped.rb
spec/fixtures/skipped.rb
# Not relevant # :nocov: # Hash.new # :nocov:
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/app/controllers/sample_controller.rb
spec/fixtures/app/controllers/sample_controller.rb
# Foo class class Foo def initialize @foo = "baz" end def bar @foo end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/app/models/user.rb
spec/fixtures/app/models/user.rb
# Foo class class Foo def initialize @foo = "baz" end def bar @foo end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/eval_test/eval_test.rb
spec/fixtures/eval_test/eval_test.rb
require "simplecov" SimpleCov.enable_coverage_for_eval SimpleCov.start "rails" file = File.join(__dir__, "eval_test.erb") erb = ERB.new(File.read(file)) erb.filename = file erb.run
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/frameworks/rspec_bad.rb
spec/fixtures/frameworks/rspec_bad.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "..", "..")) require "lib/simplecov" require "rspec" SimpleCov.print_error_status = ENV["PRINT_ERROR_STATUS"] == "true" if ENV.key? "PRINT_ERROR_STATUS" SimpleCov.start describe "exit status" do it "exits with a non-zero exit status when assertion fails" do expect(1).to eq(2) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/frameworks/rspec_good.rb
spec/fixtures/frameworks/rspec_good.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "..", "..")) require "lib/simplecov" require "rspec" SimpleCov.start describe "exit status" do it "exits with a zero exit status when assertion fails" do expect(1).to eq(1) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/frameworks/testunit_good.rb
spec/fixtures/frameworks/testunit_good.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "..", "..")) require "lib/simplecov" SimpleCov.start require "test/unit" class FooTest < Test::Unit::TestCase def test_foo assert true end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/fixtures/frameworks/testunit_bad.rb
spec/fixtures/frameworks/testunit_bad.rb
$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), "..", "..", "..")) require "lib/simplecov" SimpleCov.print_error_status = ENV["PRINT_ERROR_STATUS"] == "true" if ENV.key? "PRINT_ERROR_STATUS" SimpleCov.start require "test/unit" class FooTest < Test::Unit::TestCase def test_foo assert false end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/source_file/line_spec.rb
spec/source_file/line_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::SourceFile::Line do context "a source line" do subject do SimpleCov::SourceFile::Line.new("# the ruby source", 5, 3) end it 'returns "# the ruby source" as src' do expect(subject.src).to eq("# the ruby source") end it "returns the same for source as for src" do expect(subject.src).to eq(subject.source) end it "has line number 5" do expect(subject.line_number).to eq(5) end it "has equal line_number, line and number" do expect(subject.line).to eq(subject.line_number) expect(subject.number).to eq(subject.line_number) end context "flagged as skipped!" do before do subject.skipped! end it "is not covered" do expect(subject).not_to be_covered end it "is skipped" do expect(subject).to be_skipped end it "is not missed" do expect(subject).not_to be_missed end it "is not never" do expect(subject).not_to be_never end it "status is skipped" do expect(subject.status).to eq("skipped") end end end context "A source line with coverage" do subject do SimpleCov::SourceFile::Line.new("# the ruby source", 5, 3) end it "has coverage of 3" do expect(subject.coverage).to eq(3) end it "is covered" do expect(subject).to be_covered end it "is not skipped" do expect(subject).not_to be_skipped end it "is not missed" do expect(subject).not_to be_missed end it "is not never" do expect(subject).not_to be_never end it "status is covered" do expect(subject.status).to eq("covered") end end context "A source line without coverage" do subject do SimpleCov::SourceFile::Line.new("# the ruby source", 5, 0) end it "has coverage of 0" do expect(subject.coverage).to be_zero end it "is not covered" do expect(subject).not_to be_covered end it "is not skipped" do expect(subject).not_to be_skipped end it "is missed" do expect(subject).to be_missed end it "is not never" do expect(subject).not_to be_never end it "status is missed" do expect(subject.status).to eq("missed") end end context "A source line with no code" do subject do SimpleCov::SourceFile::Line.new("# the ruby source", 5, nil) end it "has nil coverage" do expect(subject.coverage).to be_nil end it "is not covered" do expect(subject).not_to be_covered end it "is not skipped" do expect(subject).not_to be_skipped end it "is not missed" do expect(subject).not_to be_missed end it "is never" do expect(subject).to be_never end it "status is never" do expect(subject.status).to eq("never") end end it "raises ArgumentError when initialized with invalid src" do expect { SimpleCov::SourceFile::Line.new(:symbol, 5, 3) }.to raise_error(ArgumentError) end it "raises ArgumentError when initialized with invalid line_number" do expect { SimpleCov::SourceFile::Line.new("some source", "five", 3) }.to raise_error(ArgumentError) end it "raises ArgumentError when initialized with invalid coverage" do expect { SimpleCov::SourceFile::Line.new("some source", 5, "three") }.to raise_error(ArgumentError) end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false
simplecov-ruby/simplecov
https://github.com/simplecov-ruby/simplecov/blob/afcf15e42fde20abbdb6fe9591a3e5d98acc088e/spec/source_file/branch_spec.rb
spec/source_file/branch_spec.rb
# frozen_string_literal: true require "helper" describe SimpleCov::SourceFile::Branch do let(:if_branch) do described_class.new(start_line: 1, end_line: 3, coverage: 0, inline: false, type: :then) end let(:else_branch) do described_class.new(start_line: 1, end_line: 3, coverage: 0, inline: false, type: :else) end context "a source branch if..else" do it "correct branch report" do expect(if_branch.report).to eq([:then, 0]) expect(else_branch.report).to eq([:else, 0]) end end context "A source branch with coverage" do let(:covered_branch) do described_class.new(start_line: 1, end_line: 3, coverage: 1, inline: false, type: :then) end it "is covered" do expect(covered_branch).to be_covered end it "is neither covered not missed if skipped" do covered_branch.skipped! expect(covered_branch).not_to be_covered expect(covered_branch).not_to be_missed end it "is not missed" do expect(covered_branch).not_to be_missed end end context "a source branch without coverage" do let(:uncovered_branch) do described_class.new(start_line: 1, end_line: 3, coverage: 0, inline: false, type: :then) end it "isn't covered" do expect(uncovered_branch).not_to be_covered end it "is missed" do expect(uncovered_branch).to be_missed end it "is neither covered not missed if skipped" do uncovered_branch.skipped! expect(uncovered_branch).not_to be_covered expect(uncovered_branch).not_to be_missed end end describe "skipping lines" do subject { described_class.new(start_line: 5, end_line: 7, coverage: 0, inline: false, type: :then) } it "isn't skipped by default" do expect(subject).not_to be_skipped end it "can be skipped" do subject.skipped! expect(subject).to be_skipped end end describe "#overlaps_with?(range)" do subject { described_class.new(start_line: 5, end_line: 7, coverage: 0, inline: false, type: :then) } it "doesn't overlap with a range beyond its lines" do expect(subject.overlaps_with?(8..10)).to eq false end it "doesn't overlap with a range before its lines" do expect(subject.overlaps_with?(3..4)).to eq false end it "overlaps with a range that fully includes everything" do expect(subject.overlaps_with?(1..100)).to eq true end it "overlaps with a range that exactly includes it" do expect(subject.overlaps_with?(5..7)).to eq true end it "overlaps with a range that partially includes its beginning" do expect(subject.overlaps_with?(1..5)).to eq true end it "overlaps with a range that partially includes its end" do expect(subject.overlaps_with?(7..10)).to eq true end it "overlaps with a range that pends in its middle" do expect(subject.overlaps_with?(1..6)).to eq true end end end
ruby
MIT
afcf15e42fde20abbdb6fe9591a3e5d98acc088e
2026-01-04T15:45:13.013465Z
false