Module: RSpec::Hermetic::ResourceTracker

Defined in:
lib/rspec/hermetic/resource_tracker.rb,
sig/rspec/hermetic.rbs

Defined Under Namespace

Modules: IOSingletonMethods, ProcessSingletonMethods, ThreadSingletonMethods

Constant Summary collapse

ORIGIN_IVAR =

Returns:

  • (Symbol)
:@rspec_hermetic_origin

Class Method Summary collapse

Class Method Details

.annotate(resource) ⇒ Object

Parameters:

  • resource (Object)

Returns:

  • (Object)


60
61
62
63
64
65
66
67
68
# File 'lib/rspec/hermetic/resource_tracker.rb', line 60

def annotate(resource)
  return resource unless @active
  return resource if resource.instance_variable_defined?(ORIGIN_IVAR)

  resource.instance_variable_set(ORIGIN_IVAR, caller_locations(2, 8).map(&:to_s))
  resource
rescue StandardError
  resource
end

.annotate_process(pid, command) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rspec/hermetic/resource_tracker.rb', line 70

def annotate_process(pid, command)
  return pid unless @active

  process_origins[pid] = {
    pid: pid,
    command: command.flatten.map(&:to_s).join(" "),
    origin: caller_locations(2, 8).map(&:to_s)
  }
  pid
rescue StandardError
  pid
end

.install!Object

Returns:

  • (Object)


41
42
43
44
45
46
47
48
49
# File 'lib/rspec/hermetic/resource_tracker.rb', line 41

def install!
  return if @installed

  Thread.singleton_class.prepend(ThreadSingletonMethods)
  IO.singleton_class.prepend(IOSingletonMethods)
  File.singleton_class.prepend(IOSingletonMethods)
  Process.singleton_class.prepend(ProcessSingletonMethods)
  @installed = true
end

.origin_for(resource) ⇒ Object

Parameters:

  • resource (Object)

Returns:

  • (Object)


83
84
85
86
87
# File 'lib/rspec/hermetic/resource_tracker.rb', line 83

def origin_for(resource)
  resource.instance_variable_get(ORIGIN_IVAR) if resource.instance_variable_defined?(ORIGIN_IVAR)
rescue StandardError
  nil
end

.process_alive?(pid) ⇒ Boolean

Returns:

  • (Boolean)


101
102
103
104
105
106
107
108
# File 'lib/rspec/hermetic/resource_tracker.rb', line 101

def process_alive?(pid)
  Process.kill(0, pid)
  true
rescue Errno::ESRCH, Errno::ECHILD
  false
rescue Errno::EPERM
  true
end

.process_originsObject



97
98
99
# File 'lib/rspec/hermetic/resource_tracker.rb', line 97

def process_origins
  @process_origins ||= {}
end

.start!Object

Returns:

  • (Object)


51
52
53
54
# File 'lib/rspec/hermetic/resource_tracker.rb', line 51

def start!
  install!
  @active = true
end

.stop!Object

Returns:

  • (Object)


56
57
58
# File 'lib/rspec/hermetic/resource_tracker.rb', line 56

def stop!
  @active = false
end

.tracked_processesObject



89
90
91
92
93
94
95
# File 'lib/rspec/hermetic/resource_tracker.rb', line 89

def tracked_processes
  process_origins.values.filter_map do |entry|
    next unless process_alive?(entry.fetch(:pid))

    entry
  end
end