<commit_before>Given /^there is a wire server (running |)on port (\d+) which understands the following protocol:$/ do |running, port, table|
  protocol = table.hashes.map do |table_hash|
    table_hash['response'] = table_hash['response'].gsub(/\n/, '\n')
    table_hash
  end

  @server = FakeWireServer.new(port.to_i, protocol)
  start_wire_server if running.strip == "running"
end

Given /^the wire server takes (.*) seconds to respond to the invoke message$/ do |timeout|
  @server.delay_response(:invoke, timeout.to_f)
  start_wire_server
end

Given /^I have environment variable (\w+) set to "([^"]*)"$/ do |variable, value|
  set_env(variable, value)
end

module WireHelper
  def start_wire_server
    @wire_pid = fork { @server.run }
    at_exit { stop_wire_server }
  end

  def stop_wire_server
    return unless @wire_pid
    Process.kill('KILL', @wire_pid)
    Process.wait(@wire_pid)
  end
end

Before('@wire') do
  extend(WireHelper)
end

After('@wire') do
  stop_wire_server
end<commit_msg>Be robust to wire servers that have been killed already<commit_after>Given /^there is a wire server (running |)on port (\d+) which understands the following protocol:$/ do |running, port, table|
  protocol = table.hashes.map do |table_hash|
    table_hash['response'] = table_hash['response'].gsub(/\n/, '\n')
    table_hash
  end

  @server = FakeWireServer.new(port.to_i, protocol)
  start_wire_server if running.strip == "running"
end

Given /^the wire server takes (.*) seconds to respond to the invoke message$/ do |timeout|
  @server.delay_response(:invoke, timeout.to_f)
  start_wire_server
end

Given /^I have environment variable (\w+) set to "([^"]*)"$/ do |variable, value|
  set_env(variable, value)
end

module WireHelper
  def start_wire_server
    @wire_pid = fork { @server.run }
    at_exit { stop_wire_server }
  end

  def stop_wire_server
    return unless @wire_pid
    Process.kill('KILL', @wire_pid)
    Process.wait(@wire_pid)
  rescue Errno::ESRCH
    # No such process - wire server has already been stopped by the After hook
  end
end

Before('@wire') do
  extend(WireHelper)
end

After('@wire') do
  stop_wire_server
end
{'fraction_non_alphanumeric': 0.11983279145378542, 'fraction_numerical': 0.0, 'mean_word_length': 4.177884615384615, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '922643', 'n_tokens_mistral': 730, 'n_tokens_neox': 702, 'n_words': 215}