|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "tempfile" |
| 4 | +require "pathname" |
| 5 | + |
| 6 | +RSpec.describe Singed do |
| 7 | + around do |example| |
| 8 | + original_output_directory = Singed.output_directory |
| 9 | + Singed.output_directory = Dir.mktmpdir("singed-spec") |
| 10 | + original_enabled = Singed.enabled? |
| 11 | + begin |
| 12 | + example.run |
| 13 | + ensure |
| 14 | + Singed.output_directory = original_output_directory |
| 15 | + Singed.enabled = original_enabled |
| 16 | + Singed.instance_variable_set(:@current_flamegraph, nil) |
| 17 | + end |
| 18 | + end |
| 19 | + |
| 20 | + describe ".start" do |
| 21 | + before { Singed.enabled = true } |
| 22 | + |
| 23 | + it "creates a current flamegraph and starts profiling" do |
| 24 | + current_flamegraph = Singed.start |
| 25 | + |
| 26 | + expect(current_flamegraph).to be_a(Singed::Flamegraph) |
| 27 | + expect(Singed.profiling?).to be true |
| 28 | + expect(current_flamegraph.started?).to be true |
| 29 | + end |
| 30 | + |
| 31 | + it "does nothing when already profiling" do |
| 32 | + Singed.start |
| 33 | + expect(Singed.start).to be_nil |
| 34 | + end |
| 35 | + |
| 36 | + it "does nothing when disabled" do |
| 37 | + Singed.enabled = false |
| 38 | + expect(Singed.start).to be_nil |
| 39 | + expect(Singed.profiling?).to be_falsey |
| 40 | + end |
| 41 | + end |
| 42 | + |
| 43 | + describe ".stop" do |
| 44 | + before do |
| 45 | + Singed.enabled = true |
| 46 | + Singed.output_directory = Dir.mktmpdir("singed-spec") |
| 47 | + end |
| 48 | + |
| 49 | + it "returns nil when not profiling" do |
| 50 | + expect(Singed.stop).to be_nil |
| 51 | + end |
| 52 | + |
| 53 | + it "stops profiling, saves the result file, and returns the flamegraph with profile data" do |
| 54 | + Singed.start |
| 55 | + # Run some code to generate profile samples |
| 56 | + 100.times { 2**10 } |
| 57 | + flamegraph = Singed.stop |
| 58 | + |
| 59 | + expect(flamegraph).to be_a(Singed::Flamegraph) |
| 60 | + expect(Singed.profiling?).to be false |
| 61 | + |
| 62 | + # Profile data is returned (StackProf results hash) |
| 63 | + expect(flamegraph.profile).to be_a(Hash) |
| 64 | + expect(flamegraph.profile).to include(:mode, :version, :interval) |
| 65 | + expect(flamegraph.profile[:mode]).to eq(:wall) |
| 66 | + expect(flamegraph.profile[:samples]).to be >= 0 |
| 67 | + end |
| 68 | + |
| 69 | + it "creates the result file on disk" do |
| 70 | + Singed.start |
| 71 | + 100.times { 2**10 } |
| 72 | + flamegraph = Singed.stop |
| 73 | + |
| 74 | + expect(Pathname(flamegraph.filename)).to exist |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments