Class: Moto::ThreadContext

Inherits:
Object
  • Object
show all
Defined in:
lib/thread_context.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(runner, test) ⇒ ThreadContext

Returns a new instance of ThreadContext.



12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/thread_context.rb', line 12

def initialize(runner, test)
  @runner = runner
  @test = test
  @clients = {}
  @test.context = self
  #TODO temporary fix
  Thread.current['context']= self

  @config = {}
  Dir.glob("config/*.yml").each do |f|
    @config.deep_merge! YAML.load_file(f)
  end
end

Instance Attribute Details

#current_testObject (readonly)

attr_reader :log_path



10
11
12
# File 'lib/thread_context.rb', line 10

def current_test
  @current_test
end

#loggerObject (readonly)

Returns the value of attribute logger.



8
9
10
# File 'lib/thread_context.rb', line 8

def logger
  @logger
end

#runnerObject (readonly)

all resources specific for single thread will be initialized here. E.g. browser session



7
8
9
# File 'lib/thread_context.rb', line 7

def runner
  @runner
end

Instance Method Details

#client(name) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/thread_context.rb', line 26

def client(name)
  return @clients[name] if @clients.key? name

  name_app = 'MotoApp::Clients::' + name
  name_moto = 'Moto::Clients::' + name

  c = try_client(name_app, "#{MotoApp::DIR}/lib")
  unless c.nil?
    @clients[name] = c
    return c
  end

  c = try_client(name_moto, "#{Moto::DIR}/lib")
  unless c.nil?
    @clients[name] = c
    return c
  end
  raise "Could not find client class for name #{name}"
end

#const(key) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/thread_context.rb', line 64

def const(key)
  key = key.to_s
  key = "#{@current_test.env.to_s}.#{key}" if @current_test.env != :__default
  code = if key.include? '.'
    "@config#{key.split('.').map{|a| "['#{a}']" }.join('')}"
  else
    "@config['#{key}']"
  end
  begin
    v = eval code
    raise if v.nil?
  rescue
    raise "There is no const defined for key: #{key}. Environment: #{ (@current_test.env == :__default) ? '<none>' : @current_test.env }"
  end
  v
end

#runObject



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# File 'lib/thread_context.rb', line 81

def run
  # remove log/screenshot files from previous execution
  Dir.glob("#{@test.dir}/*.{log,png}").each {|f| File.delete f }
  max_attempts = @runner.my_config[:max_attempts] || 1
  sleep_time = @runner.my_config[:sleep_before_attempt] || 0
  @runner.environments.each do |env|
    params_all = [{}]

    # YAML config files
    #params_path = "#{@test.dir}/#{@test.filename}_params.yml"
    #params_all = YAML.load(ERB.new(File.read(params_path)).result) if File.exists?(params_path)

    # RB Config files
    params_path = "#{@test.dir}/#{@test.filename}"
    params_all = eval(File.read(params_path)) if File.exists?(params_path)

    params_all.each_with_index do |params, params_index|
      # Filtering out param sets that are specific to certain envs
      unless params['__env'].nil?
        allowed_envs = params['__env'].is_a?(String) ? [params['__env']] : params['__env'] 
        next unless allowed_envs.include? env
      end
      (1..max_attempts).each do |attempt|
        @test.init(env, params, params_index)
        # TODO: log path might be specified (to some extent) by the configuration
        @test.log_path = "#{@test.dir}/#{@test.name.gsub(/\s+/, '_').gsub('::', '_').gsub('/', '_')}.log"
        @logger = Logger.new(File.open(@test.log_path, File::WRONLY | File::TRUNC | File::CREAT))
        @logger.level = @runner.my_config[:log_level] || Logger::DEBUG
        @current_test = @test
        @runner.listeners.each { |l| l.start_test(@test) }
        @clients.each_value { |c| c.start_test(@test) }
        @test.before
        @logger.info "Start: #{@test.name} attempt #{attempt}/#{max_attempts}"
        begin
          @test.run
        rescue Exceptions::TestForcedPassed, Exceptions::TestForcedFailure, Exceptions::TestSkipped => e
          logger.info(e.message)
          @runner.result.add_error(@test, e)
        rescue Exception => e
          @logger.error("#{e.class.name}: #{e.message}")
          @logger.error(e.backtrace.join("\n"))
          @clients.each_value { |c| c.handle_test_exception(@test, e) }
          @runner.result.add_error(@test, e)
        end
        @test.after
        @clients.each_value { |c| c.end_test(@test) }
        # HAX: running end_test on results now, on other listeners after logger is closed
        @runner.listeners.first.end_test(@test)
        @logger.info("Result: #{@test.result}")
        @logger.close
        @runner.listeners[1..-1].each { |l| l.end_test(@test) }
        break unless [Result::FAILURE, Result::ERROR].include? @test.result
        sleep sleep_time unless attempt.equal? max_attempts
      end # RETRY
    end
  end
  @clients.each_value { |c| c.end_run }
end

#try_client(name, dir) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/thread_context.rb', line 46

def try_client(name, dir)
  begin
    a = name.underscore.split('/')
    client_path = a[1..-1].join('/')
    require "#{dir}/#{client_path}"
    client_const = name.constantize
    instance = client_const.new(self)
    instance.init
    instance.start_run
    instance.start_test(@current_test)
    return instance
  rescue Exception => e
    # puts e
    # puts e.backtrace
    return nil
  end
end