|
| 1 | +require "test_helper" |
| 2 | + |
| 3 | +class Railsdb::Admin::StatsTest < ActiveSupport::TestCase |
| 4 | + setup do |
| 5 | + Railsdb::Admin::EventStore.instance.clear |
| 6 | + @stats_klass = Railsdb::Admin::Stats |
| 7 | + end |
| 8 | + |
| 9 | + test "returns an array of hashes" do |
| 10 | + Product.all.to_a |
| 11 | + catalog = Catalog.create!(title: "Catalog", available: true) |
| 12 | + Product.create!(name: "Product", code: 100, catalog: catalog) |
| 13 | + |
| 14 | + stats = @stats_klass.fetch_avg_durations |
| 15 | + assert_equal(3, stats.size) |
| 16 | + end |
| 17 | + |
| 18 | + test "returns one event for product creation" do |
| 19 | + catalog = Catalog.create!(title: "Catalog", available: true) |
| 20 | + Product.create!(name: "Product", code: 100, catalog: catalog) |
| 21 | + Product.create!(name: "Product good", code: 101, catalog: catalog) |
| 22 | + |
| 23 | + stats = @stats_klass.fetch_avg_durations |
| 24 | + assert_equal(2, stats.size) |
| 25 | + end |
| 26 | + |
| 27 | + test "returns sql query" do |
| 28 | + Product.all.to_a |
| 29 | + |
| 30 | + stats = @stats_klass.fetch_avg_durations |
| 31 | + |
| 32 | + first_event = "SELECT \"products\".* FROM \"products\"" |
| 33 | + assert_equal(first_event, stats.first[:sql]) |
| 34 | + end |
| 35 | + |
| 36 | + def create_events |
| 37 | + event = ActiveSupport::Notifications::Event.new("sql.active_record", |
| 38 | + 10.seconds.ago, |
| 39 | + 3.seconds.ago, |
| 40 | + 1, |
| 41 | + { sql: "SELECT * FROM products" }) |
| 42 | + event_2 = ActiveSupport::Notifications::Event.new("sql.active_record", |
| 43 | + 10.seconds.ago, |
| 44 | + 5.seconds.ago, |
| 45 | + 6, |
| 46 | + { sql: "SELECT * FROM products" }) |
| 47 | + Railsdb::Admin::EventStore.instance.add_event(event) |
| 48 | + Railsdb::Admin::EventStore.instance.add_event(event_2) |
| 49 | + end |
| 50 | + |
| 51 | + test "calculates avg duration" do |
| 52 | + create_events |
| 53 | + stats = @stats_klass.fetch_avg_durations |
| 54 | + |
| 55 | + assert_equal(6000, stats.first[:avg_duration].to_i) |
| 56 | + end |
| 57 | + |
| 58 | + test "counts the amount of query calls" do |
| 59 | + create_events |
| 60 | + stats = @stats_klass.fetch_avg_durations |
| 61 | + |
| 62 | + assert_equal(2, stats.first[:count]) |
| 63 | + end |
| 64 | +end |
0 commit comments