Unable to use any_instance on Twitter gem's user_timline - ruby

I am still quite fresh to Ruby, and especially testing in Ruby. Hopefully the code is not a trainwreck :) I am having issues using any_instance with the Twitter gem, while it works fine on my own classes.
This is (what I believe) the relevant code
require 'twitter'
require 'minitest/unit'
require 'mocha/mini_test'
omitting for brevity....
args = { id: 573536452149182464, id_str: 73536452149182464, text: 'This is an initial tweet from the user'}
initial_tweet = ::Twitter::Tweet.new(args)
::Twitter::REST::Timelines.any_instance.stubs(:user_timeline).returns(initial_tweet)
The code produces the following error:
Minitest::UnexpectedError: NoMethodError: undefined method `any_instance|' for Twitter::REST::Timelines:Module
Are principles to stubbing gems different, am I approaching it wrong?
EDIT: I have added the entire code for the two classes below.
twitter.rb
require 'rubygems'
require 'cinch'
require 'cinch/commands'
require 'twitter'
require 'shorturl'
module Gigabot
module Commands
class Twitter
include Cinch::Plugin
include Cinch::Commands
def initialize(bot)
super(bot)
#client = create_client
#follow = config[:follow]
#channels = bot.config.channels
#latest_tweets = Hash.new
set_initial_tweets
end
timer 60, method: :twitter_update
def twitter_update
#follow.each do |user|
new_tweet = #client.user_timeline(user, options = {exclude_replies: true}).first
if #latest_tweets[user] != new_tweet
short_url = ShortURL.shorten("https://twitter.com/#{user}/status/#{new_tweet.id}")
reply = Format(:bold, "<#{user}> ") + "#{new_tweet.full_text} [#{short_url}]"
reply = reply.gsub(/\n/,' ')
#channels.each {|channel| Channel(channel).send(reply)}
#latest_tweets[user] = new_tweet
end
end
end
private
def create_client
::Twitter::REST::Client.new do |c|
c.consumer_key = config[:consumer_key]
c.consumer_secret = config[:consumer_secret]
c.access_token = config[:access_token]
c.access_token_secret = config[:access_token_secret]
end
end
def set_initial_tweets
#follow.each do |user|
#latest_tweets[user] = #client.user_timeline(user, options = {exclude_replies: true}).first
end
end
end
end
end
twitter_test.rb
require 'twitter'
require 'minitest/unit'
require 'mocha/mini_test'
require File.dirname(__FILE__) + '/../../../helper'
require File.dirname(__FILE__) + '/../../../../lib/gigabot/commands/twitter'
module Gigabot
module Commands
class TwitterTest < TestCase
def setup
bot = Cinch::Bot.new
bot.loggers.level = :fatal
bot.config.plugins.options[Twitter] = {
consumer_key: 'test_key',
consumer_secret: 'test_key_secret',
access_token: 'test_access_token',
access_token_secret: 'test_access_token_secret',
follow: %w(follow1 follow2)
}
args = { id: 573536452149182464, id_str: 73536452149182464, text: 'This is an initial tweet from the user'}
initial_tweet = ::Twitter::Tweet.new(args)
::Twitter::REST::Timelines.any_instance.stubs(:user_timeline).returns(initial_tweet)
#plugin = Twitter.new(bot)
end
def test_create_twitter_client_on_initialize
refute_nil(#plugin.instance_variable_get(:#client))
end
end
end
end

Related

assert_equal not working with selenium and ruby

I am writing a script using selenium tool in ruby. and I am trying to use assert_equal property of selenium to test pass or failure status of my test. below is my file
require 'selenium-webdriver'
require 'test-unit'
$driver = Selenium::WebDriver.for :firefox
$project_url = "http://www.example.com"
class Travelibro
def initialize
Login.run
end
end
class Login <
##pop_up_xpath = "/html/body/div[5]/div[1]/div[3]/p/a"
##email_xpath = "//input[#name='user[email]']"
##password_xpath = "//input[#name='user[password]']"
##click_button_class = "loginBtn"
##login_email = "mailtohemant#yahoo.co.in"
##login_password = "password"
def self.run
login = Login.new
login.blank_email_or_password
end
def blank_email_or_password
open_login_pop_up = $driver.find_element(:xpath,"#{##pop_up_xpath}")
open_login_pop_up.click
email = $driver.find_element(:xpath, "#{##email_xpath}")
email.send_keys "#{##login_email}"
password = $driver.find_element(:xpath, "#{##password_xpath}")
password.send_keys "#{##login_password}"
submit_form = $driver.find_element(:class,"#{##click_button_class}")
submit_form.click
isPresent = $driver.find_elements(:class,"signInError").size() > 0
assert_equal($driver.find_elements(:xpath => "/html/body/div[6]/div[2]/div/div/ul/li[1]/a")[0].text, "vin")
result = {}
result[:test_name] = "Login Test"
result[:inputs] = "blank email or password"
result[:test_result] = isPresent ? "Pass" : "Failed"
result.each do |key, value|
puts "#{key}:#{value}"
end
end
end
travelibro = Travelibro.new
what is the wrong. I am getting this error,
/gems/test-unit-3.1.8/lib/test/unit/testcase.rb:430:in `initialize': wrong number of arguments (0 for 1) (ArgumentError)
The problem is that you are trying to create instance of class inherited from Test::Unit::TestCase (I think it's typo that it's empty in code).
The right way to use test-unit gem would be removing Travelibro class, removing Login test construction and renaming blank_email_or_password method to test_black_email_or_password.
require 'selenium-webdriver'
require 'test-unit'
$driver = Selenium::WebDriver.for :firefox
$project_url = "http://www.example.com"
class Login < Test::Unit::TestCase
##pop_up_xpath = "/html/body/div[5]/div[1]/div[3]/p/a"
##email_xpath = "//input[#name='user[email]']"
##password_xpath = "//input[#name='user[password]']"
##click_button_class = "loginBtn"
##login_email = "mailtohemant#yahoo.co.in"
##login_password = "password"
def test_blank_email_or_password
open_login_pop_up = $driver.find_element(:xpath,"#{##pop_up_xpath}")
open_login_pop_up.click
email = $driver.find_element(:xpath, "#{##email_xpath}")
email.send_keys "#{##login_email}"
password = $driver.find_element(:xpath, "#{##password_xpath}")
password.send_keys "#{##login_password}"
submit_form = $driver.find_element(:class,"#{##click_button_class}")
submit_form.click
isPresent = $driver.find_elements(:class,"signInError").size() > 0
assert_equal($driver.find_elements(:xpath => "/html/body/div[6]/div[2]/div/div/ul/li[1]/a")[0].text, "vin")
result = {}
result[:test_name] = "Login Test"
result[:inputs] = "blank email or password"
result[:test_result] = isPresent ? "Pass" : "Failed"
result.each do |key, value|
puts "#{key}:#{value}"
end
end
end
Or if you are inheriting not from Test::Unit::TestCase, you can just override constructor, and class will be created successfully
def initialize
end

Ruby: const_set outside block?

I want to mock a class with Ruby.
How do I write a method that will take care of the boilerplate code?
The following code:
module Mailgun
end
module Acani
def self.mock_mailgun(mock)
temp = Mailgun
const_set(:Mailgun, mock)
p Mailgun
yield
ensure
const_set(:Mailgun, temp)
end
end
Acani.mock_mailgun('mock') { p Mailgun }
prints:
"mock"
Mailgun
What's going on here? Why is Mailgun its original value inside the block? Does this have to do with Ruby bindings?
Ruby version: 2.1.1p76
Try putting Object. before each const_set.
The code in the question is simplified. Here is the pertinent code:
test/test_helper.rb
require 'minitest/autorun'
module Acani
def self.const_mock(const, mock)
temp = const_get(const)
const_set_silent(const, mock)
yield
ensure
const_set_silent(const, temp)
end
private
def self.const_set_silent(const, value)
temp = $VERBOSE
$VERBOSE = nil
Object.const_set(const, value)
ensure
$VERBOSE = temp
end
end
test/web_test.rb
require 'test_helper'
require 'rack/test'
require_relative '../web'
class AppTest < MiniTest::Test
include Rack::Test::Methods
def app
Sinatra::Application
end
def test_password_reset
post '/users', {email: 'user1#gmail.com', password: 'password1'}
mailgun_mock = MiniTest::Mock.new
mailgun_mock.expect(:send, 200, [Hash])
Acani.const_mock(:Mailgun, mailgun_mock) do
post '/password_resets', {email: 'user1#gmail.com'}
end
mailgun_mock.verify
assert_equal 201, last_response.status
end
end

Ruby inheriting a module class not working

I'm trying to write a class "web" in Ruby 2.0.0 that inherits from GEXF::Graph, but I am unable to get the Graph methods like Web.define_node_attribute to work. I'm a new ruby programmer, so I expect I'm doing something goofy. Thanks.
webrun.rb
require 'rubygems'
require 'gexf'
require 'anemone'
require 'mechanize'
require_relative 'web'
web = Web.new
web.define_node_attribute(:url)
web.define_node_attribute(:links,
:type => GEXF::Attribute::BOOLEAN,
:default => true)
web.rb
require 'rubygems'
require 'gexf'
require 'anemone'
require 'mechanize'
class Web < GEXF::Graph
attr_accessor :root
attr_accessor :pages
def initialize
#pages = Array.new
end
def pages
#pages
end
def add page
#pages << page
end
def parse uri, protocol = 'http:', domain = 'localhost', file = 'index.html'
u = uri.split('/')
if n = /^(https?:)/.match(u[0])
protocol = n[0]
u.shift()
end
if u[0] == ''
u.shift()
end
if n = /([\w\.]+\.(org|com|net))/.match(u[0])
domain = n[0]
u.shift()
end
if n = /(.*\.(html?|gif))/.match(u[-1])
file = n[0]
u.pop()
end
cnt = 0
while u[cnt] == '..' do
cnt = cnt + 1
u.shift()
end
while cnt > 0 do
cnt = cnt - 1
u.shift()
end
directory = '/'+u.join('/')
puts "protocol: " + protocol + " domain: " + domain + \
" directory: " + directory + " file: " + file
protocol + "//" + domain + directory + (directory[-1] == '/' ? '/' : '') + file
end
def crawl
Anemone.crawl(#root) do |anemone|
anemone.on_every_page do |sitepage|
add sitepage
end
end
end
def save file
f = File.open(file, mode = "w")
f.write(to_xml)
f.close()
end
end
The issue is that you are monkey-patching the GEXF::Graph initialize method without calling super on it. What you did was essentially 'write-over' the initialize method that needed to be called. To fix this, change your initialize method to call the super method first:
def initialize
super
#pages = Array.new
end

Implement caching in Sinatra app to handle twitter rate limits

I have written a small Sinatra script to fetch 2 tweets of a user and display 10 retweeters in the descending order of their no. of followers:
Puzzle/puzzle.rb
require 'twitter'
require 'json'
require 'sinatra'
#require 'haml'
client = Twitter::REST::Client.new do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.access_token = ""
config.access_token_secret = ""
end
set :server, 'webrick'
set :haml, :format => :html5
get '/' do
content_type :json
arr = []
retweeters = client.retweeters_of(429627812459593728)
retweeters.each do |retweeter|
ob = {}
ob[:name] = retweeter.name
ob[:followers_count] = retweeter.followers_count
arr.push(ob)
end
# remove the duplicates and sort on the users with the most followers,
sorted_influencers = arr.sort_by { |hsh| hsh[:followers_count] }
sorted_influencers.reverse!
sorted_influencers[0..9].to_s
end
I am trying to handle rate limits.
How to cache the json output to avoid rate limit exceeding?
Assuming you keep your very simple scenario, you could use a small custom class to store the information and provide thread-safe methods (it is not clear from your question where your problem exactly resides, but this one problem will arise anyway):
require 'json'
require 'sinatra'
require 'date'
require 'thread'
require 'twitter'
set :server, 'webrick'
set :haml, :format => :html5
class MyCache
def initialize()
#mutex = Mutex.new
#last_update = DateTime.new # by default, -4732 BC
#client = Twitter::REST::Client.new do |config|
config.consumer_key = ""
config.consumer_secret = ""
config.access_token = ""
config.access_token_secret = ""
end
end
def get_cache
#mutex.synchronize do
if DateTime.now - #last_update > 10.0 / (3600 * 24)
#last_update = DateTime.now
arr = []
retweeters = #client.retweeters_of(429627812459593728)
retweeters.each do |retweeter|
ob = {}
ob[:name] = retweeter.name
ob[:followers_count] = retweeter.followers_count
arr.push(ob)
end
# remove the duplicates and sort on the users with the most followers,
sorted_influencers = arr.sort_by { |hsh| hsh[:followers_count] }
sorted_influencers.reverse!
#cache = sorted_influencers[0..9].to_s
end
#cache
end
end
end
my_cache = MyCache.new
get '/' do
content_type :json
my_cache.get_cache
end
This version now includes everything needed. I use the #client to store the instance of the twitter client (I suppose it's reusable), also note how the whole code is inside the if statement, and at last we update #cache. If you are unfamiliar with Ruby, the value of a block is determined by its last expression, so when I write #cache alone it is as if I had written return #cache.

Sinatra app doesnt redirect to haml files

This is the Sinatra code that I wrote. All gems exist, the ruby files compiles perfectly but when i go to localhost:4567/ the sinatra app doesnt run. It takes me to the 'Sinatra doesnt know this ditty' page. What mistake am i making here? Is it a syntax issue? I've posted the main ruby file's code here others are just haml files thats all.
require 'bundler'
Bundler.setup(:default)
require 'sinatra'
require 'haml'
require 'twitter'
require 'oauth'
class MyTweetWeek < Sinatra::Base
set :haml, :format => :html5, :attr_wrapper => '"'
enable :sessions, :static, :raise_errors
set :public_dir, File.join(File.dirname(__FILE__), 'public')
get '/' do
haml :index
end
get '/login' do
request_token = consumer.get_request_token(:oauth_callback => ENV['OAUTH_CALLBACK'])
session[:request_token] = request_token.token
session[:request_token_secret] = request_token.secret
redirect request_token.authorize_url
end
get '/oauth_callback' do
request_token = OAuth::RequestToken.new(
consumer,
session[:request_token],
session[:request_token_secret]
)
session[:request_token] = session[:request_token_secret] = nil
access_token = request_token.get_access_token(:oauth_verifier => params[:oauth_verifier])
session[:access_token] = access_token.token
session[:access_secret] = access_token.secret
redirect '/resume'
end
get '/resume' do
redirect '/' unless authenticated?
today = Date.today #get today's date
monday = today - today.cwday + 1 #calculate Monday
search = Twitter::Search.new
#screen_name = client.verify_credentials.screen_name
#number_of_tweets = 0
#number_of_mentions = 0
results = search.from(#screen_name)
.since_date(monday)
.no_retweets
.per_page(100)
.fetch
#number_of_tweets += results.size
while search.next_page?
results = search.fetch_next_page
#number_of_tweets += results.size
end
search.clear
results = search.q("##{#screen_name.gsub('#', '')}")
.since_date(monday)
.no_retweets
.per_page(100)
.fetch
#number_of_mentions += results.size
while search.next_page?
results = search.fetch_next_page
#number_of_mentions += results.size
end
haml :resume
end
error Twitter::Error::Unauthorized do
redirect '/'
end
not_found do
haml :not_found
end
private
def consumer
#consumer ||= OAuth::Consumer.new(
ENV['CONSUMER_KEY'],
ENV['CONSUMER_SECRET'],
:site => "https://api.twitter.com"
)
end
def client
Twitter.configure do |config|
config.consumer_key = ENV['CONSUMER_KEY']
config.consumer_secret = ENV['CONSUMER_SECRET']
config.oauth_token = session[:access_token]
config.oauth_token_secret = session[:access_secret]
end
#client ||= Twitter::Client.new
end
def authenticated?
!session[:access_token].nil? && !session[:access_secret].nil?
end
end
As you have a modular app do you need to require "sinatra/base" rather than "sinatra"? See here
See Serving a Modular App and add the line run! if app_file == $0 at the end of the class. Also see DavB's answer.

Resources