Skip to content

Instantly share code, notes, and snippets.

@LeipeLeon
Created June 11, 2021 09:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LeipeLeon/629a75b78fa42161d21ef362c38f08fb to your computer and use it in GitHub Desktop.
Save LeipeLeon/629a75b78fa42161d21ef362c38f08fb to your computer and use it in GitHub Desktop.
# Taken from https://thoughtbot.com/blog/how-to-stub-external-services-in-tests
require 'sinatra/base'
class FakeMuxApi < Sinatra::Base
configure :production, :development do
enable :logging
end
post '/video/v1/assets' do
payload = JSON.parse(request.body.read).symbolize_keys
plain_json_response 200, { data: {
"status": "preparing",
"source_asset_id": "sadfasdfasdlkgfdy7g798a6sd8f6786asd57a",
"playback_ids": [
{
"policy": "signed",
"id": "sxfd6gx8adsz89v6arg89hex7ry9gs67v9da"
}
],
"passthrough": "encoder:9 client_reference:ZXGRDTFJDRSTHGERY event:94",
"mp4_support": "standard",
"master_access": "temporary",
"id": "XEGZERFCWDTXTAXTEGZR",
"created_at": 1617305279
} }
end
get '/video/v1/assets/:id' do
json_response 200, "asset.find.%s.json" % params[:id]
end
delete '/video/v1/assets/:id' do
plain_json_response 204, {}
end
put '/video/v1/live-streams/:id/disable' do
plain_json_response 200, { data: {} }
end
put '/video/v1/live-streams/:id/enable' do
plain_json_response 200, { data: {} }
end
get '/video/v1/delivery-usage' do
if params[:timeframe][0].to_i < (Time.current - 90.days).beginning_of_day.to_i
status 400
'{"error":{"type":"invalid_parameters","messages":["invalid timeframe: start time must be in the last 90 days"]}}"}'
else
start = I18n.l(Time.at(params[:timeframe][0].to_i), format: "%Y%m%d-%H%M")
stop = I18n.l(Time.at(params[:timeframe][1].to_i), format: "%Y%m%d-%H%M")
file_name = "delivery-usage.%s.%s.%s.json" % [params[:asset_id], start, stop]
json_response 200, file_name
end
end
# Catch all Routes
get '/*' do
throw [:GET, params]
end
post '/*' do
throw [:POST, params]
end
put '/*' do
throw [:PUT, params]
end
# start the server if ruby file executed directly
run! if app_file == $0
private
def plain_json_response(response_code, hash)
content_type "application/json"
status response_code
hash.to_json
end
def json_response(response_code, file_name)
content_type "application/json"
file_path = Rails.root.join('spec', 'fixtures', 'mux', 'api', "#{file_name}")
if File.exist?(file_path)
status response_code
File.open(file_path, 'rb').read
else
$stdout.puts "404 Not Found: #{file_path}"
status 404
"404 Not Found: #{file_path}"
end
rescue => e
abort(e.message)
end
end
require_relative 'support/fake_mux_api.rb'
WebMock.disable_net_connect!(allow_localhost: true)
RSpec.configure do |config|
config.before(:each) do
stub_request(:any, /api\.mux\.com/).to_rack(FakeMuxApi)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment