Class: Vizzly::Client

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server_url: nil) ⇒ Client

Returns a new instance of Client.



17
18
19
20
21
# File 'lib/vizzly.rb', line 17

def initialize(server_url: nil)
  @server_url = server_url || discover_server_url
  @disabled = false
  @warned = false
end

Instance Attribute Details

#disabledObject (readonly)

Returns the value of attribute disabled.



15
16
17
# File 'lib/vizzly.rb', line 15

def disabled
  @disabled
end

#server_urlObject (readonly)

Returns the value of attribute server_url.



15
16
17
# File 'lib/vizzly.rb', line 15

def server_url
  @server_url
end

Instance Method Details

#disable!(reason = 'disabled') ⇒ Object

Disable screenshot capture

Parameters:

  • reason (String) (defaults to: 'disabled')

    Optional reason for disabling



153
154
155
156
157
158
# File 'lib/vizzly.rb', line 153

def disable!(reason = 'disabled')
  @disabled = true
  return if reason == 'disabled'

  warn "Vizzly SDK disabled due to #{reason}. Screenshots will be skipped for the remainder of this session."
end

#disabled?Boolean

Check if screenshot capture is disabled

Returns:

  • (Boolean)


163
164
165
# File 'lib/vizzly.rb', line 163

def disabled?
  @disabled
end

#flushtrue

Wait for all queued screenshots to be processed (Simple client doesn’t need explicit flushing)

Returns:

  • (true)


139
140
141
# File 'lib/vizzly.rb', line 139

def flush
  true
end

#infoHash

Get client information

Returns:

  • (Hash)

    Client state information



170
171
172
173
174
175
176
177
178
# File 'lib/vizzly.rb', line 170

def info
  {
    enabled: !disabled?,
    server_url: @server_url,
    ready: ready?,
    build_id: ENV.fetch('VIZZLY_BUILD_ID', nil),
    disabled: disabled?
  }
end

#ready?Boolean

Check if the client is ready to capture screenshots

Returns:

  • (Boolean)


146
147
148
# File 'lib/vizzly.rb', line 146

def ready?
  !disabled? && !@server_url.nil?
end

#screenshot(name, image_data, options = {}) ⇒ Hash?

Take a screenshot for visual regression testing

Examples:

client = Vizzly::Client.new
image_data = File.binread('screenshot.png')
client.screenshot('homepage', image_data)

With options

client.screenshot('checkout', image_data,
  properties: { browser: 'chrome', viewport: { width: 1920, height: 1080 } },
  threshold: 5
)

Parameters:

  • name (String)

    Unique name for the screenshot

  • image_data (String)

    PNG image data as binary string

  • options (Hash) (defaults to: {})

    Optional configuration

Options Hash (options):

  • :properties (Hash)

    Additional properties to attach

  • :threshold (Integer)

    Pixel difference threshold (0-100)

  • :full_page (Boolean)

    Whether this is a full page screenshot

Returns:

  • (Hash, nil)

    Response data or nil if disabled/failed



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
# File 'lib/vizzly.rb', line 44

def screenshot(name, image_data, options = {})
  return nil if disabled?

  unless @server_url
    warn_once('Vizzly client not initialized. Screenshots will be skipped.')
    disable!
    return nil
  end

  image_base64 = Base64.strict_encode64(image_data)

  payload = {
    name: name,
    image: image_base64,
    buildId: ENV.fetch('VIZZLY_BUILD_ID', nil),
    threshold: options[:threshold] || 0,
    fullPage: options[:full_page] || false,
    properties: options[:properties] || {}
  }.compact

  uri = URI("#{@server_url}/screenshot")

  begin
    response = Net::HTTP.start(uri.host, uri.port, read_timeout: 30) do |http|
      request = Net::HTTP::Post.new(uri)
      request['Content-Type'] = 'application/json'
      request.body = JSON.generate(payload)
      http.request(request)
    end

    unless response.is_a?(Net::HTTPSuccess)
      error_data = begin
        JSON.parse(response.body)
      rescue JSON::ParserError, StandardError
        {}
      end

      # In TDD mode with visual differences, log but don't raise
      if response.code == '422' && error_data['tddMode'] && error_data['comparison']
        comp = error_data['comparison']
        diff_percent = comp['diffPercentage']&.round(2) || 0.0

        # Extract port from server_url
        port = begin
          @server_url.match(/:(\d+)/)[1]
        rescue StandardError
          DEFAULT_TDD_PORT.to_s
        end
        dashboard_url = "http://localhost:#{port}/dashboard"

        warn "⚠️  Visual diff: #{comp['name']} (#{diff_percent}%) → #{dashboard_url}"

        return {
          success: true,
          status: 'failed',
          name: comp['name'],
          diffPercentage: comp['diffPercentage']
        }
      end

      raise Error,
            "Screenshot failed: #{response.code} #{response.message} - #{error_data['error'] || 'Unknown error'}"
    end

    JSON.parse(response.body)
  rescue Error => e
    # Re-raise Vizzly errors (like visual diffs)
    raise if e.message.include?('Visual diff')

    warn "Vizzly screenshot failed for #{name}: #{e.message}"

    if e.message.include?('Connection refused') || e.is_a?(Errno::ECONNREFUSED)
      warn "Server URL: #{@server_url}/screenshot"
      warn 'This usually means the Vizzly server is not running or not accessible'
      warn 'Check that the server is started and the port is correct'
    elsif e.message.include?('404') || e.message.include?('Not Found')
      warn "Server URL: #{@server_url}/screenshot"
      warn 'The screenshot endpoint was not found - check server configuration'
    end

    # Disable the SDK after first failure to prevent spam
    disable!('failure')

    nil
  rescue StandardError => e
    warn "Vizzly screenshot failed for #{name}: #{e.message}"
    disable!('failure')
    nil
  end
end